Underscore debounce vs vanilla Javascript setTimeout

nikjohn picture nikjohn · Apr 11, 2016 · Viewed 11.3k times · Source

I understand that debounce in Undercore.js returns a function that will postpone its execution until the wait time is over.

My question is, is there an advantage of using debounce over the regular setTimeout function in vanilla Javascript? Don't they both work the same?

Answer

Avinash picture Avinash · Apr 11, 2016

They are very different and used in completely different cases.

  1. _.debounce returns a function, setTimeout returns an id which you can use to cancel the timeOut.

  2. No matter how many times you call the function which is returned by _.debounce, it will run only once in the given time frame.

var log_once = _.debounce(log, 5000);

function log() {
  console.log('prints');
}

log_once();
log_once();
log_once();
log_once();
log_once();

var id = setTimeout(function() {
  console.log('hello');
}, 3000);
clearTimeout(id);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>