Last active
December 20, 2016 22:03
-
-
Save sylvainpolletvillard/497c3d9d7cc8d85246a0ef5320b43368 to your computer and use it in GitHub Desktop.
debounce.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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