JavaScript: Debounce callback’s execution by `limit` milliseconds

Posted on

In case you want execute event listener’s callback after given amount of time (milliseconds), you may find LoDash’ _.debounce function extremely useful.

Sample Usage:

1) Define Callback:

function windowResized() {
  console.log('window resized');

2) Set milliseconds limit:

var limit = 300; // 300 milliseconds

3) Bind Event Listener (callback):

window.addEventListener('resize', _.debounce(windowResized, limit), false);

That’s it! Now slowly resize your browser’s window. Callback shouldn’t execute until you stop resizing for at least 300ms!

Leave a Reply

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