Function debounce

  • Executes a function when it stops being invoked for n seconds. Usually used together with resize, scroll and keyup/keydown-events to improve application's performance.

    Example:

       window.addEventListener(
    'resize',
    debounce(computationalHeavyFunction, 1000),
    );

    This will call the computationalHeavyFunction once if the resize-event hasn't been sent for 1000 ms.

    Example with immediate-flag:

       window.addEventListener(
    'resize',
    debounce(computationalHeavyFunction, 1000, true),
    );

    This will call the computationalHeavyFunction once BEFORE the resize-event has finished, and thereafter will not be able to be called again until the timeout has finished

    Type Parameters

    • TThis
    • TArgs extends unknown[]
    • TReturn

    Parameters

    • this: TThis
    • func: ((this: TThis, ...args: TArgs) => TReturn)

      Function to be debounced.

    • delay: number

      Function execution threshold in milliseconds.

    • immediate: boolean = false

      Whether the function should be called at the beginning of the delay (Before the timeout) instead of the end. Default is false.

    Returns ((...args: TArgs) => void)

      • (...args): void
      • Parameters

        Returns void