Last active
June 6, 2025 18:57
-
-
Save erikvullings/f1b0af465f32fefdbd29348e0bea8e18 to your computer and use it in GitHub Desktop.
Debounce a function, i.e. wait for a certain amount of time before executing the function. Often used when frequent edits would trigger a function multiple times, you can use this to wait for a certain amount of time before executing the 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
/** | |
* Debounce a function, i.e. wait for a certain amount of time before executing the function. | |
* Often used when frequent edits would trigger a function multiple times, you can use this to | |
* wait for a certain amount of time before executing the function. | |
* | |
* @param func The function to be debounced. | |
* @param delay The delay in milliseconds for the debounce. | |
* @returns A function that debounces the original function. | |
* @example const debouncedFunc = debounce(myFunction, 100); debouncedFunc(args); | |
*/ | |
export const debounce = <T extends Function & ((...args: any) => any)>( | |
/** The function to be debounced. */ | |
func: T, | |
/** The delay in milliseconds for the debounce. */ | |
delay: number | |
): ((...args: Parameters<T>) => void) => { | |
let timeout: number | null; | |
return ((...args: Parameters<T>) => { | |
if (timeout) { | |
clearTimeout(timeout); | |
} | |
timeout = setTimeout(() => { | |
func(...args); | |
}, delay); | |
}) as unknown as (...args: Parameters<T>) => void; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment