Open In App

Lodash _.debounce() Method

Lodash _.debounce() method is used to create a debounced function that delays the given function until after the stated wait time in milliseconds has passed since the last time this debounced 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 that is used to immediately call the delayed function. It also provides some options that can be used to imply whether the function stated should be called on the leading and/or the trailing edge of the wait timeout.



Note:

Syntax:

_.debounce( func, wait, options{})

Parameters:

Return Value:

This method returns the new debounced function.

Example 1: In this example, the function will be called after 1000ms as mentioned in the lodash.debounce() function.






// Requiring lodash library
const lodash = require('lodash');
 
// Using lodash.debounce() method
// with its parameters
let debounce_fun = lodash.debounce(function () {
    console.log('Function debounced after 1000ms!');
}, 1000);
 
debounce_fun();

Output:

Function debounced after 1000ms!

Example 2: In this example, both optional parameters are true that’s why function is executing immediately without following the specified time.




// Requiring lodash library
const _ = require('lodash');
 
// Using _.debounce() method
// with its parameters
let debounced_fun = _.debounce(function () {
    console.log("function is executing immideately!!")
}, 5000, { leading: true, trailing: true });
debounced_fun();

Output:

function is executing immideately!!

Article Tags :