Function throttle

  • Reduces the number of calls to a given function. Can be used for "debouncing", "throttling", as well as other common scenarios where we wish to restrict the number of times a function can be called.

    This function can also be accessed like an object. This gives fine-grained control over the cooldown behavior and more, allowing the user to manually clear or reset the cooldown. As an example, this may be useful for implementing a throttle that waits on an external dependency, such as a server response.

    Example

    Basic usage

    let i = 1;
    function originalFunction() {
    console.log(i++);
    }
    const throttledFunction = throttle(originalFunction, { cooldownMs: 500 });
    throttledFunction(); // calls originalFunction immediately, starts the cooldown period
    throttledFunction(); // cooldown in progress... queue a call for when it is complete
    throttledFunction(); // call is already queued! Ignore.
    throttledFunction(); // call is already queued! Ignore.
    throttledFunction.clearCooldown(); // Force the cooldown to end, causing the queued call to execute.
    throttledFunction(); // cooldown in progress... queue a call for when it is complete

    // output:
    // 1
    // 2
    // <500ms passes>
    // 3

    Returns

    Type Parameters

    • TArgs extends unknown[]

    • TReturn

    Parameters

    • fn: ((...args: TArgs) => TReturn)
        • (...args: TArgs): TReturn
        • Parameters

          • Rest ...args: TArgs

          Returns TReturn

    • settings: Partial<ThrottleSettings> = {}

    Returns ThrottledFunction<TArgs, TReturn>

Generated using TypeDoc