• Creates a throttled function that invokes func at most once per wait milliseconds.

    Type Parameters

    • T extends (...args: unknown[]) => unknown

      The function type to throttle.

    Parameters

    • func: T

      The function to throttle.

    • wait: number

      Milliseconds to throttle invocations to.

    Returns DebouncedFunction<T>

    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;
    }