Debounce is a programming pattern that restricts a function from being called again until a certain amount of time has passed without it being called. This is particularly useful for optimizing performance in scenarios where a function might be called frequently, such as during window resizing, scrolling, or user input events.
const debounce = <T extends (...args: any[] => any)(func: T, waitFor: number) => {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>): ReturnType<T> => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func(args);
}, waitFor);
};
}