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?
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.
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.
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.
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.
They are very different and used in completely different cases.
_.debounce
returns a function
, setTimeout
returns an id
which you can use to cancel the timeOut.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With