Lodash debounce example

To ensure that a Javascript function only gets called once ever few seconds, you can run run it through debounce:

function run() {
   console.log('abc');
}
 
var realFunction = 
  _.debounce(run, 1500);
 
realFunction();
realFunction();
realFunction();

Output is:

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.

function run(a) {
   console.log(a);
}
 
var realFunction = 
  _.debounce(run, 1500);
 
realFunction('a');
realFunction('b');
realFunction('c');

Output is:

c

By default, debounce waits the interval before making the call.

If you want it to run immediately without a pause (if possible) do this:

var realFunction = 
  _.debounce(run, 1500, {leading: true});
 
realFunction('a'); 
realFunction('b'); 
realFunction('c');

Prints out:

a

If you want a good Javascript book, I got a lot out of Secrets of the Javascript Ninja.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *