Gary Sieling

Lodash debounce example

To ensure that a JavaScript function is not called more than once every few seconds, you can run wrap it it in the “debounce” function available in lodash:

const run = () =>
   console.log('abc');

const lag = 
  _.debounce(run, 1500);

lag();
lag();
lag();

The output will be:

abc

In this case, the function will only get run once.

If you pass an argument, it will be sent through to the function, but still only one call is made. This is why these work well as click handlers.

const run = (a) => 
   console.log(a);

const fn = 
  _.debounce(run, 1500);

fn('a');
fn('b');
fn('c');

The output will be:

c

By default, debounce calls the function at the end of the interval.

If it to run at the beginning of the interval without a pause, do this:

const fn = 
  _.debounce(run, 500, {leading: true});

fn('a'); 
fn('b'); 
fn('c');

This will display the following:

a
Exit mobile version