Created
August 22, 2022 20:51
-
-
Save abelflopes/ff19310a793a36b572991a4fd1a1cbed to your computer and use it in GitHub Desktop.
Typescript debounce
This file contains 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
type TimeOutSheet = Record<string, ReturnType<typeof setTimeout | typeof clearTimeout>>; | |
const timeOutSheet: TimeOutSheet = {}; | |
const getFnId = (fn: () => unknown): string => { | |
return [fn.name, fn.toString()].join("").split(" ").join(""); | |
}; | |
export const debounce = (callback: () => void, ms: number): void => { | |
const toId = timeOutSheet[getFnId(callback)]; | |
if (toId) clearTimeout(toId); | |
const id = setTimeout(callback, ms); | |
timeOutSheet[getFnId(callback)] = id; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment