Skip to content

Instantly share code, notes, and snippets.

@beshur
Created December 3, 2015 18:37
Show Gist options
  • Save beshur/d54ef67bdb74ccbcb131 to your computer and use it in GitHub Desktop.
Save beshur/d54ef67bdb74ccbcb131 to your computer and use it in GitHub Desktop.
javascript debounce
/**
* Debounce creates a FUNCTION that when invoked, delays invoking func for wait milliseconds since
* the last time it is called.
*
* Examples of where this may be useful:
*
* // Avoiding repeated costly operations while a window size is in flux
* jQuery(window).on('resize', debounce(calculateLayout, 150));
*
* // Avoiding triggering an event on a double button press
* jQuery('#postbox').on('click', debounce(sendMail, 2000));
*
* @param {number} func
* @param {number} milliseconds
* @retun {function} a function that will wait {@param wait} milliseconds since it's last called
* to invoke {@param func}.
*/
function debounce(func, wait, maxWait) {
var timeoutId,
timeoutIdMax;
return function() {
if (timeoutId) {
window.clearTimeout(timeoutId);
}
if (!timeoutIdMax) {
timeoutIdMax = window.setTimeout(function () {
window.clearTimeout(timeoutId);
func();
}, maxWait); // you want to make sure foo executes and timeoutId is cancelled
}
timeoutId = window.setTimeout(function() {
func();
if (timeoutIdMax) window.clearTimeout(timeoutIdMax);
}, wait); // you want to make sure foo executes maxTimeoutId is cancelled
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment