Created
March 6, 2024 03:08
-
-
Save jeremy-code/2c6f2d9d1910543d8e8f25aa15a1d51e to your computer and use it in GitHub Desktop.
debounce.ts
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
export function debounce<T extends (...args: Parameters<T>) => ReturnType<T>>( | |
callback: T, | |
wait: number, | |
immediate?: boolean | |
): (...args: Parameters<T>) => void { | |
let timeout: NodeJS.Timeout | undefined; | |
return function (this: ThisParameterType<T>, ...args: Parameters<T>): void { | |
const later = () => { | |
timeout = undefined; | |
if (!immediate) callback.apply(this, args); | |
}; | |
const callNow = immediate && timeout === undefined; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) callback.apply(this, args); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment