Last active
January 21, 2021 19:04
-
-
Save LucasIron/d715f4b7f141fce722659c3061dcbcf3 to your computer and use it in GitHub Desktop.
Debounce & Throttle
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
debounce = (delay, cancel) => (listener, wait) => { | |
let delayId | |
return function(...args) { | |
cancel(delayId) | |
return delayId = delay(() => listener.apply(this, args), wait) | |
} | |
} | |
debounceTimeout = debounce(setTimeout, clearTimeout) | |
debounceAnimationFrame = debounce(requestAnimationFrame, cancelAnimationFrame) | |
throttle = (delay, cancel) => (listener, wait) => { | |
let throttling | |
let delayId | |
let before | |
return function(...args) { | |
const now = Date.now() | |
if (!throttling) { | |
listener.apply(this, args) | |
before = now | |
throttling = true | |
} else { | |
cancel(delayId) | |
return delayId = delay(() => { | |
if (now - before >= wait) { | |
listener.apply(this, args) | |
before = now | |
} | |
}, wait - now - before) | |
} | |
} | |
} | |
throttleTimeout = throttle(setTimeout, clearTimeout) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment