Skip to content

Instantly share code, notes, and snippets.

@pryley
Created Sep 23, 2021
Embed
What would you like to do?
Debounce function
export function Debounce (fn: Function, wait = 200) {
let timerId: number
let lastArgs: Array<any> | undefined
let lastCallTime: DOMHighResTimeStamp
let lastThis
let result
const startTimer = (pendingFunc: FrameRequestCallback) => {
cancelAnimationFrame(timerId)
return requestAnimationFrame(pendingFunc)
}
const timerExpired = () => {
const timeSinceLastCall = performance.now() - lastCallTime
if (timeSinceLastCall >= wait || timeSinceLastCall < 0) {
result = fn.apply(lastThis, lastArgs)
lastArgs = lastThis = void 0
return result
}
timerId = startTimer(timerExpired)
}
return (...args: Array<any>) => {
lastArgs = args
lastCallTime = performance.now()
lastThis = this
if (timerId === void 0) {
timerId = startTimer(timerExpired)
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment