Created
September 23, 2021 09:34
-
-
Save pryley/c822c23ec542b6d7b6196de4707c3bdf to your computer and use it in GitHub Desktop.
Debounce function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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