The _.debounce() Function in Underscore.js is used to create a debounced function that is used to delay the execution of the given function until after the given wait time in milliseconds have passed since the last time this function was called. The debounced function has a cancel method that can be used to cancel the function calls that are delayed and a flush method which is used to immediately call the delayed function.
Syntax:
_.debounce( function, wait, immediate )
Parameter: This function accepts three parameters as mentioned above and described below:
- function: It is the function that has to be debounced.
- wait: It is the number of milliseconds for which the calls are to be delayed. It is an optional parameter. The default value is 0.
- immediate: It is the boolean which specifies that the debounced function would be called at the beginning of the sequence instead of the end. It is an optional parameter.
Return Value: This method returns the new debounced function.
The example below illustrates the _.debounce() function is Underscore.js.
Example 1:
HTML
< html > < head > < script src = </ script > </ head > < body > < h1 style = "color: green" >neveropen</ h1 > < h3 >Underscore _.debounce() Function</ h3 > < button onclick = "debounce_fn()" > Click to debounce function </ button > < script type = "text/javascript" > var debounce_fn = _.debounce(debounceHandler, 2000, false); function debounceHandler() { console.log('Hello Geeks!') } </ script > </ body > </ html > |
Output:
Example 2:
HTML
< html > < head > < script src = </ script > </ head > < body > < h1 style = "color: green" >neveropen</ h1 > < h3 >Underscore _.debounce() Function</ h3 > < button onclick = "debounce_fn()" > Click to debounce function </ button > < script type = "text/javascript" > var debounce_fn = _.debounce(debounceHandler, 2000, true); function debounceHandler() { console.log('Hello Geeks Immediately!') } </ script > </ body > </ html > |
Output:
Reference: https://underscorejs.org/#debounce