Skip to content

Instantly share code, notes, and snippets.

@ZatsuneNoMokou
Forked from beshur/debounce.js
Last active September 10, 2017 09:28
Show Gist options
  • Save ZatsuneNoMokou/6d0af1783c348facde59c92c53a63b1f to your computer and use it in GitHub Desktop.
Save ZatsuneNoMokou/6d0af1783c348facde59c92c53a63b1f to your computer and use it in GitHub Desktop.
javascript debounce
/**
* Debounce creates a FUNCTION that when invoked, delays invoking fn for wait milliseconds since
* the last time it is called.
*
* @param {number} fn - function to call
* @param {number} wait - duration in milliseconds
* @param {number} maxWait - max duration in milliseconds before calling {@param fn}
* @retun {function} a function that will wait {@param wait} milliseconds since it's last called to invoke {@param fn}.
*/
function debounce(fn, wait, maxWait=null) {
var timeoutId = null,
timeoutIdMax = null;
return function() {
var context = this, args = arguments;
if (timeoutId!==null) {
window.clearTimeout(timeoutId);
}
if (maxWait!==null && timeoutIdMax===null) {
timeoutIdMax = window.setTimeout(function () {
window.clearTimeout(timeoutId);
timeoutId = timeoutIdMax = null;
fn.apply(context, args);
}, maxWait); // you want to make sure foo executes and timeoutId is cancelled
}
timeoutId = window.setTimeout(function() {
window.clearTimeout(timeoutId);
timeoutId = null;
fn.apply(context, args);
if (maxWait!==null && timeoutIdMax!==null){
window.clearTimeout(timeoutIdMax);
timeoutIdMax = null;
}
}, 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