TS-Scribe - v1.2.0
    Preparing search index...

    Function debounce

    • Creates a debounced version of a function, which will only be invoked after a specified delay has passed since the last time the debounced function was invoked. If immediate is true, the function will be triggered at the start of the debounce delay, otherwise, it is triggered after.

      Each call returns a Promise that resolves with the function's return value when that specific invocation leads to execution. Calls that are cancelled by a subsequent invocation within the wait window resolve with undefined.

      This is useful for scenarios like limiting the rate of user input handling, resizing events, or scroll events.


      Example:

      const handleSearch = debounce((searchTerm: string) => {
      console.log('Searching for:', searchTerm);
      return searchTerm;
      }, 500);

      handleSearch('a'); // cancelled
      handleSearch('ab'); // cancelled
      const result = await handleSearch('abc'); // resolves with 'abc'

      Type Parameters

      • T extends unknown[]
      • R

      Parameters

      • fn: (...args: T) => R

        The function to debounce.

      • wait: number

        The number of milliseconds to wait before invoking the function after the last call.

      • immediate: boolean = false

        If true, the function will be triggered at the beginning of the debounce period.

      Returns (...args: T) => Promise<R | undefined>

      A debounced version of the input function. Each call returns a Promise that resolves with the function's return value, or undefined if the call was cancelled by a subsequent call.

      const debouncedLog = debounce((msg: string) => console.log(msg), 1000, true);
      debouncedLog("Hello"); // Immediately logs "Hello", then waits for 1000ms for further calls