A project I've been working on uses _.debounce().
The Underscore JS documentation for debounce reads as follows:
debounce
_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked.
This obviously assumes that anyone who wants to know what debounce()
does, already knows what 'debounce' means.
What does debounce actually do?
The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called.
js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _. mean() method is used to find the mean of the values in the array. Syntax: _.mean( array )
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.
The debounced function has a cancel method that can be used to cancel the func calls that are delayed and a flush method which is used to immediately call the delayed func.
Basically it throttles calls so if it is called more than once in a short period of time, only one instance will be called.
Why would you use it?
Events like window.onresize fire multiple times in rapid succession. If you need to do a lot of calculations on the new position, you would not want to fire the calculations multiple times. You only want to fire it when the user has finished the resizing event.
Description from the source code of underscore.js:
Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If 'immediate' is passed, trigger the function on the leading edge, instead of the trailing.
Code it self:
_.debounce = function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) result = func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) result = func.apply(context, args); return result; }; };
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