Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Last active December 20, 2016 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sylvainpolletvillard/497c3d9d7cc8d85246a0ef5320b43368 to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/497c3d9d7cc8d85246a0ef5320b43368 to your computer and use it in GitHub Desktop.
debounce.js
function debounce(func, wait = 20, options) {
options = Object.assign({
leading: false,
trailing: true,
throttle: false
}, options);
let timeout, isWaiting = false;
return function debounced(...args) {
if (!timeout && options.leading) func.apply(this, args);
if (timeout) isWaiting = true;
if (timeout && !options.throttle) {
clearTimeout(timeout);
timeout = null;
isWaiting = false;
}
if(!isWaiting){
timeout = setTimeout(() => {
if(options.trailing || (options.throttle && isWaiting)) func.apply(this, args);
let wasWaiting = isWaiting;
timeout = null;
isWaiting = false;
if(options.throttle && wasWaiting) debounced(...args);
}, wait);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment