The debounce method from underscore library isn't working as expected, how do I create a function that can only be called once a second?

50 views Asked by At

I am trying to understand how debounce works, but it does not seem to do what I think it would do.

Here is an example

const fn = _.debounce(
  () => {
    document.getElementById("result").innerHTML = count
    count += 1
  },
  1000,
  true
);

let count = 0

function loop() {
  setTimeout(loop, 0);
  fn();
}

loop();
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
<div>
  Hello World
</div>
<div id="result"></div>

I expect that this would setup a debounce function that can only be called once every second, so I expect result to get updated the the current count each second.

However, it only runs it once, so result stays at 0 the entire time.

Am I misunderstanding how this function works?

0

There are 0 answers