Skip to content

Instantly share code, notes, and snippets.

@ZatsuneNoMokou
Forked from beshur/debounce.js
Last active January 19, 2025 11:31
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.
*
* @see https://gist.github.com/ZatsuneNoMokou/6d0af1783c348facde59c92c53a63b1f/617ccd3e858446983aa166b322ccb30319cf6dd8
* @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) {
let timeoutId = null,
timeoutIdMax = null;
return function() {
const context = this, args = arguments;
if (timeoutId !== null) self.clearTimeout(timeoutId);
if (maxWait !== null && timeoutIdMax === null) {
timeoutIdMax = self.setTimeout(function () {
self.clearTimeout(timeoutId);
timeoutId = timeoutIdMax = null;
fn.apply(context, args);
}, maxWait); // you want to make sure foo executes and timeoutId is cancelled
}
timeoutId = self.setTimeout(function() {
self.clearTimeout(timeoutId);
timeoutId = null;
fn.apply(context, args);
if (maxWait !== null && timeoutIdMax !== null){
self.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