The debounce()
function forces a function to wait a certain amount of time before running again.
The function is built to limit the number of times a function is called.
Events such as scrolling, mouse movement, and keypress bring great overhead with them if they are captured every single time they fire. The function aims to reduce overhead by preventing a function from being called several times in succession.
The following implementation of debounce
returns a function that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If immediate
is passed as an argument to the function, the function triggers immediately and then waits for the interval before being called again.
function debounce(func, wait, immediate) {var timeout;return function executedFunction() {var context = this;var args = arguments;var later = function() {timeout = null;if (!immediate) func.apply(context, args);};var callNow = immediate && !timeout;clearTimeout(timeout);timeout = setTimeout(later, wait);if (callNow) func.apply(context, args);};};
On passing a function and a time interval to debounce, a function is returned that can be passed on to the event listeners that execute the function.
var returnedFunction = debounce(function() {// The function's code}, 250);window.addEventListener('resize', returnedFunction);
The following example displays an alert box 2 seconds after the user has stopped pressing the button. It passes the debounced function to the button’s onClick
event handler.