The function to throttle.
Milliseconds to throttle invocations to.
Throttled function with optional cancel method.
export function throttle<T extends (...args: unknown[]) => unknown>(
func: T,
wait: number,
): DebouncedFunction<T> {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let lastArgs: Parameters<T> | null = null;
function throttled(...args: Parameters<T>): void {
lastArgs = args;
if (timeoutId === null) {
func(...args);
timeoutId = setTimeout(() => {
if (lastArgs !== null) {
func(...lastArgs);
}
timeoutId = null;
lastArgs = null;
}, wait);
}
}
throttled.cancel = (): void => {
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
lastArgs = null;
}
};
return throttled;
}
Creates a throttled function that invokes func at most once per wait milliseconds.