Tweakr
    Preparing search index...

    Function debouncePromise

    • Debounces a promise-returning function.

      This function ensures that the provided async function fn is only invoked once per wait milliseconds, regardless of how many times the returned function is called within that period. All calls within the wait period will resolve with the same result of the last invocation.

      Type Parameters

      • T extends (...args: any[]) => Promise<any>

        A function type that returns a Promise.

      Parameters

      • fn: T

        The async function to debounce.

      • wait: number

        The debounce interval in milliseconds.

      Returns (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>

      A new function that wraps fn with debounce behavior. Each call returns a Promise that resolves to the result of fn.

      1.1.0

      const fetchData = async (id: number) => {
      console.log('Fetching', id);
      return id * 2;
      };

      const debouncedFetch = debouncePromise(fetchData, 200);

      debouncedFetch(1).then(console.log); // Will log 2
      debouncedFetch(2).then(console.log); // Will also log 4 after 200ms, previous call resolves with 4 too