Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore debounce vs vanilla Javascript setTimeout

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?

like image 556
nikjohn Avatar asked Apr 11 '16 12:04

nikjohn


People also ask

Does debounce use setTimeout?

Each time the debounced function is invoked, clear the current pending timeout with clearTimeout() . Use setTimeout() to create a new timeout that delays invoking the function until at least ms milliseconds have elapsed.

What is the alternative for setTimeout in Javascript?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.

What is Javascript Debounce?

Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page. In other words, it limits the rate at which a function gets invoked.

Does setTimeout block execution?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.


2 Answers

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>
like image 77
Avinash Avatar answered Sep 18 '22 15:09

Avinash


setTimeout and debounce are in no way the same thing. setTimeout simply waits n milliseconds and the invokes the supplied function. debounce on the other hand returns a function that only calls the callback after n milliseconds after the last time the functions was called.

Huge difference. Debouncing/throttling (they are not the same thing) functions are often used to reduced the amount of function calls as a result of user input. Imagine a autocomplete/typeahead field. You might do an ajax request every keystroke, but that can get kind of heavy, so instead you can debounce the function, so it will only fire 200ms after the last keystroke.

You can read up on the documentation here: https://lodash.com/docs#debounce

like image 33
Phillip Avatar answered Sep 17 '22 15:09

Phillip