Last Updated: February 25, 2016
·
2.268K
· maciejsmolinski

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

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!

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside