Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does _.debounce do?

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?

like image 299
mikemaccana Avatar asked Apr 10 '13 13:04

mikemaccana


People also ask

What does _ debounce () 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.

What does _ mean in Lodash?

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 )

Why do we use 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.

What does debounce flush do?

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.


2 Answers

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.

like image 200
epascarello Avatar answered Oct 03 '22 05:10

epascarello


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;   }; }; 
like image 37
JackPoint Avatar answered Oct 03 '22 05:10

JackPoint