Pauses execution for interval after which the asynchronous callback is executed and awaited. Must be called with await if you want the pause effect.
callback
await
const result = await delay(async () => Math.random(), 1000);console.log(result); // Prints out result after one second Copy
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:
interval
const result = await delay(async () => Math.random(), { mins: 1 }); Copy
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. Copy
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.
delay()
sleep()
Optionally takes an AbortSignal to cancel delay.
const ac = new AbortController();// Super long waitawait delay(someFn, { signal: ac.signal, hours: 1 }}...ac.abort(); // Cancels long delay Copy
const ac = new AbortController();// Super long waitawait 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.
Type of callback return value
What to run after interval
Options for delay, or millisecond delay. By default delay is before callback is executed.
Returns result of callback.
Pauses execution for interval after which the asynchronous
callback
is executed and awaited. Must be called withawait
if you want the pause effect.Example: Pause and wait for function
If the
interval
option is a number its treated as milliseconds. Interval can also be used:If
await
is omitted, the function will run after the provided timeout, and code will continue to run.Example: Schedule a function without waiting
delay and sleep are similar.
delay()
takes a parameter of what code to execute after the timeout, whilesleep()
just resolves after the timeout.Optionally takes an AbortSignal to cancel 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.