A lightweight utility to delay a promise for a specified amount of time. It's a modern alternative to setTimeout inside an async function.
npm install @se-oss/delayInstall using your favorite package manager
pnpm
pnpm install @se-oss/delayyarn
yarn add @se-oss/delayimport delay from '@se-oss/delay';
console.log('Waiting...');
await delay(1000);
console.log('Done!');The returned promise resolves with a value.
import delay from '@se-oss/delay';
const result = await delay(100, { value: '🦄' });
console.log(result);
//=> '🦄'Delay for a random amount of time within a specified range.
import { rangeDelay } from '@se-oss/delay';
console.log('Waiting for a random time between 100ms and 200ms...');
await rangeDelay(100, 200);
console.log('Done!');You can clear a delay before it resolves.
import delay, { clearDelay } from '@se-oss/delay';
const delayedPromise = delay(1000, { value: 'done' });
setTimeout(() => {
clearDelay(delayedPromise);
}, 500);
const result = await delayedPromise;
// The promise resolves immediately with 'done' when cleared.
console.log(result);
//=> 'done'Abort a delay using an AbortSignal.
import delay from '@se-oss/delay';
const controller = new AbortController();
setTimeout(() => {
controller.abort();
}, 500);
try {
await delay(1000, { signal: controller.signal });
} catch (error) {
console.log(error.name); // 500 milliseconds later
//=> 'AbortError'
}Returns a promise that resolves after the specified milliseconds.
Type: number
The number of milliseconds to delay.
Type: object
Type: T
A value to resolve in the returned promise.
Type: AbortSignal
An AbortSignal to abort the delay. The returned promise will be rejected with the signal's reason if the signal is aborted.
Returns a promise that resolves after a random amount of time between minimum and maximum milliseconds.
Type: number
The minimum number of milliseconds to delay.
Type: number
The maximum number of milliseconds to delay.
Same options as delay.
Clears a pending delay. The promise will resolve immediately with its configured value.
Type: Promise<unknown>
The promise returned from delay() or rangeDelay().
Creates a new delay instance with custom setTimeout and clearTimeout functions.
Type: object
Type: (callback: (...args: any[]) => void, milliseconds: number, ...args: any[]) => unknown
A custom setTimeout function.
Type: (timeoutId: any) => void
A custom clearTimeout function.
Want to contribute? Awesome! To show your support is to star the project, or to raise issues on GitHub
Thanks again for your support, it is much appreciated! 🙏
MIT © Shahrad Elahi and contributors.