Skip to content

Instantly share code, notes, and snippets.

@LucasIron
Last active January 21, 2021 19:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LucasIron/d715f4b7f141fce722659c3061dcbcf3 to your computer and use it in GitHub Desktop.
Save LucasIron/d715f4b7f141fce722659c3061dcbcf3 to your computer and use it in GitHub Desktop.
Debounce & Throttle
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