Skip to content

Instantly share code, notes, and snippets.

@Mix-Liten
Created April 5, 2022 10:42
Show Gist options
  • Save Mix-Liten/d08fe2260069728f9edcc9e166840a70 to your computer and use it in GitHub Desktop.
Save Mix-Liten/d08fe2260069728f9edcc9e166840a70 to your computer and use it in GitHub Desktop.
Throttle Function
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