The function to debounce.
Milliseconds to delay invocation.
Debounced function with cancel method.
export function debounce<T extends (...args: unknown[]) => unknown>(
func: T,
wait: number,
): DebouncedFunction<T> {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
function debounced(...args: Parameters<T>): void {
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func(...args);
timeoutId = null;
}, wait);
}
debounced.cancel = (): void => {
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
};
return debounced;
}
Creates a debounced function that delays invocation until after wait milliseconds have elapsed since the last call.