Function debounce

  • Creates a debounced version of the provided function.

    A debounced function delays the execution of the given func until after delay milliseconds have elapsed since the last time the debounced function was invoked. This is useful for rate-limiting events like resizing, scrolling, or typing.

    Type Parameters

    • F extends (...args: Parameters<F>) => ReturnType<F>

      The type of the function to debounce.

    Parameters

    • func: F

      The function to debounce.

    • delay: number

      The delay in milliseconds before the function is executed.

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

    A debounced version of the function.

    // Create a debounced function
    const log = (message: string) => console.log(message);
    const debouncedLog = debounce(log, 300);

    // Call the debounced function multiple times
    debouncedLog("Hello"); // Will not immediately log
    debouncedLog("World"); // Previous call is canceled

    // After 300ms of no calls, "World" will be logged