[!TIP]
If you target Node.js only, you can use import {setTimeout} from 'node:timers/promises'; await setTimeout(1000); instead. This package can still be useful if you need browser support or the extra features.
Install
npm install delay
Usage
import delay from 'delay';bar();await delay(100);// Executed 100 milliseconds laterbaz();
API
delay(milliseconds, options?) default import
Create a promise which resolves after the specified milliseconds.
rangeDelay(minimum, maximum, options?)
Create a promise which resolves after a random amount of milliseconds between minimum and maximum has passed.
Useful for tests and web scraping since they can have unpredictable performance. For example, if you have a test that asserts a method should not take longer than a certain amount of time, and then run it on a CI, it could take longer. So with this method, you could give it a threshold instead.
milliseconds
mininum
maximum
Type: number
Milliseconds to delay the promise.
Unlike native setTimeout, this supports unlimited delay length.
options
Type: object
value
Type: unknown
A value to resolve in the returned promise.
import delay from 'delay';const result = await delay(100, {value: '🦄'});// Executed after 100 millisecondsconsole.log(result);//=> '🦄'
Creates a new delay instance using the provided functions for clearing and setting timeouts. Useful if you're about to stub timers globally, but you still want to use delay to manage your tests.
import {createDelay} from 'delay';const customDelay = createDelay({clearTimeout, setTimeout});const result = await customDelay(100, {value: '🦄'});// Executed after 100 millisecondsconsole.log(result);//=> '🦄'