Skip to content

Instantly share code, notes, and snippets.

@aryankarim
Last active April 9, 2022 06:07
Show Gist options
  • Save aryankarim/8f5aacf2d177b0eb2ef2edfd2569ab16 to your computer and use it in GitHub Desktop.
Save aryankarim/8f5aacf2d177b0eb2ef2edfd2569ab16 to your computer and use it in GitHub Desktop.
Debounce and Throttle
function debounce(cb, wait = 1000) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(cb(...args), wait);
}
}
function throttle(cb, delay = 1000) {
let shouldWait = false
let waitingArgs
const timeoutFunc = () => {
if (waitingArgs == null) {
shouldWait = false
} else {
cb(...waitingArgs)
waitingArgs = null
setTimeout(timeoutFunc, delay)
}
}
return (...args) => {
if (shouldWait) {
waitingArgs = args
return
}
cb(...args)
shouldWait = true
setTimeout(timeoutFunc, delay)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment