goldies
    Preparing search index...

    Function throttle

    • Creates a function that calls fn at most once every wait milliseconds.

      The first call runs right away. Calls during the wait are combined into one call at the end of it, with the latest arguments, so the final state is never lost. Use it for events that fire continuously, such as scrolling, when you want regular updates during them. To run only once a burst is over, use debounce.

      Type Parameters

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

      Parameters

      • fn: F

        The function to throttle. Its return value is ignored.

      • wait: number

        The minimum time between calls, in milliseconds.

      • options: ThrottleOptions = {}

        Whether to call right away (leading) and at the end of the wait (trailing).

      Returns ThrottledFunction<F>

      The throttled function, with cancel() and flush() methods.

      const savePosition = throttle(() => {
      localStorage.setItem('scroll', String(window.scrollY));
      }, 500);

      window.addEventListener('scroll', savePosition);