Skip to content

Instantly share code, notes, and snippets.

@pryley
Created September 23, 2021 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pryley/c822c23ec542b6d7b6196de4707c3bdf to your computer and use it in GitHub Desktop.
Save pryley/c822c23ec542b6d7b6196de4707c3bdf to your computer and use it in GitHub Desktop.
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