Lodash Debounce

Create a debounced function that delays the given function

·

2 min read

The _.debounce() method of Function in lodash 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.

Syntax:

_.debounce( func, wait, options )

Parameters: This method accepts three parameters as mentioned above and described below:

  • func: 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.
  • options: It is the options object that can be used for changing the behaviour of the method. It is an optional parameter.

The options object has the following parameters:

  • leading: It defines the calling on the leading edge of the timeout. It is an optional parameter. The default value is false.
  • maxWait: It is the maximum number of time for which the func is allowed to be delayed before it is called. It is an optional parameter.
  • trailing: It defines the calling on the trailing edge of the timeout. It is an optional parameter. The default value is true.
// Requiring lodash library
const _ = require('lodash');

// Using _.debounce() method
// with its parameters
var debounce_fun = _.debounce(function() {
  console.log('Function debounced after 1000ms!');
  }, 4, 1000, {'leading': false});

// Defining loop
var loop = function() {
    setTimeout(loop, 3)
    debounce_fun();
};

// Calling loop to start
loop();