• Creates a debounced function that immediately invokes on the leading edge and delays subsequent calls. Useful for operations that should happen immediately but also batch follow-up calls.

    Type Parameters

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

      The function type to debounce.

    Parameters

    • func: T

      The function to debounce.

    • wait: number

      Milliseconds to delay subsequent invocations.

    Returns (...args: Parameters<T>) => void

    Debounced function with immediate leading call.

    export function debounceImmediate<T extends (...args: unknown[]) => unknown>(
    func: T,
    wait: number,
    ): (...args: Parameters<T>) => void {
    let timeoutId: ReturnType<typeof setTimeout> | null = null;
    let isFirstCall = true;

    return function debouncedImmediate(...args: Parameters<T>): void {
    if (isFirstCall) {
    func(...args);
    isFirstCall = false;
    }

    if (timeoutId !== null) {
    clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(() => {
    func(...args);
    timeoutId = null;
    isFirstCall = true;
    }, wait);
    };
    }