JS Throttle Explained
Ning Kuang
1 min read
Init:
var
shouldWait
defaults tofalse
var
waitingArgs
defaults tonull
return a function that
if
shouldWait
, setwaitingArgs
to current invocation's args, then returnif not
shouldWait
:run the callback immediately
set
shouldWait
totrue
set a timer with
delay
to do the following things (described intimeoutCallback
):if there aren't
waitingArgs
, just flipshouldWait
tofalse
otherwise, run the callback immediately; clear
waitingArgs
; then set a timer to recursively invoke self
function throttle(callback, delay) {
let shouldWait = false
let waitingArgs = null
const timeoutCallback = () => {
if (waitingArgs === null) {
shouldWait = false
return
}
callback.apply(this, waitingArgs)
waitingArgs = null
setTimeout(timeoutCallback, delay)
}
return (...args) => {
if (shouldWait) {
waitingArgs = args
return
}
callback.apply(this, args)
shouldWait = true
setTimeout(timeoutCallback, delay)
}
}
1
Subscribe to my newsletter
Read articles from Ning Kuang directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by