0

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
zrbecker
  • 1,394
  • 1
  • 19
  • 39
  • Looks like what I want is _.throttle – zrbecker Feb 11 '23 at 00:12
  • 1
    I think you're confusing debouncing with throttling. See [here](https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function) for the difference. – Barmar Feb 11 '23 at 00:27

0 Answers0