ixfx
    Preparing search index...

    Function delay

    • Pauses execution for interval after which the asynchronous callback is executed and awaited. Must be called with await if you want the pause effect.

      Type Parameters

      • V

        Type of callback return value

      Parameters

      • callback: () => Promise<V>

        What to run after interval

      • optsOrMillis: number | DelayOpts

        Options for delay, or millisecond delay. By default delay is before callback is executed.

      Returns Promise<V>

      Returns result of callback.

      const result = await delay(async () => Math.random(), 1000);
      console.log(result); // Prints out result after one second

      If the interval option is a number its treated as milliseconds. Interval can also be used:

      const result = await delay(async () => Math.random(), { mins: 1 });
      

      If await is omitted, the function will run after the provided timeout, and code will continue to run.

      await delay(async () => {
      console.log(Math.random())
      }, 1000);
      // Prints out a random number after 1 second.

      delay and sleep are similar. delay() takes a parameter of what code to execute after the timeout, while sleep() just resolves after the timeout.

      Optionally takes an AbortSignal to cancel delay.

      const ac = new AbortController();
      // Super long wait
      await delay(someFn, { signal: ac.signal, hours: 1 }}
      ...
      ac.abort(); // Cancels long delay

      It also allows choice of when delay should happen. If you want to be able to cancel or re-run a delayed function, consider using timeout instead.