@se-oss/delay is a lightweight utility to delay a promise for a specified amount of time, offering a modern alternative to setTimeout.
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';
await delay(1000);The returned promise resolves with a specified value.
import delay from '@se-oss/delay';
const result = await delay(100, { value: '☕' });
console.log(result);
//=> '☕'Retrieve the actual execution drift (difference between requested and actual delay).
import delay from '@se-oss/delay';
const { value, stats } = await delay(100, { value: '☕', stats: true });
console.log(stats.drift);
//=> 2 (milliseconds)Delay for a random amount of time within a specified range.
import { rangeDelay } from '@se-oss/delay';
await rangeDelay(100, 200);Clear a pending delay to resolve it immediately.
import delay, { clearDelay } from '@se-oss/delay';
const promise = delay(1000, { value: '☕' });
// Sometime later...
clearDelay(promise);
const result = await promise;
//=> '☕'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);
//=> 'AbortError'
}For all configuration options, please see the API docs.
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.