• Creates a debounced function that delays invocation until after wait milliseconds have elapsed since the last call.

    Type Parameters

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

      The function type to debounce.

    Parameters

    • func: T

      The function to debounce.

    • wait: number

      Milliseconds to delay invocation.

    Returns DebouncedFunction<T>

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