goldies
    Preparing search index...

    Function debounce

    • Creates a function that waits until calls stop for wait milliseconds, then calls fn once with the latest arguments.

      Use it for events that fire in bursts, such as typing or resizing, when only the final state matters. To run at a steady rate during a burst instead, use throttle.

      Type Parameters

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

      Parameters

      • fn: F

        The function to debounce. Its return value is ignored.

      • wait: number

        How long calls must stop for, in milliseconds.

      • options: DebounceOptions = {}

        Whether to call on the first call of a burst (leading) and after it (trailing).

      Returns DebouncedFunction<F>

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

      const search = debounce((query: string) => fetchResults(query), 300);

      input.addEventListener('input', () => search(input.value));

      // Leaving the page: drop the search that hasn't run yet
      search.cancel();