What is delay?
The 'delay' npm package is a simple utility that allows you to pause the execution of an asynchronous function for a specified amount of time. It is primarily used to introduce delays in promise chains or async functions, making it useful for testing, rate limiting, or creating time-based behavior in applications.
What are delay's main functionalities?
Basic Delay
This feature allows you to pause the execution of code within an async function for a specified duration (in milliseconds). In this example, the code waits for 2 seconds before printing '2 seconds later'.
const delay = require('delay');
(async () => {
console.log('Waiting...');
await delay(2000);
console.log('2 seconds later');
})();
Delay with Value
This feature enables you to resolve a promise with a specific value after a delay. Here, the promise resolves with the string 'Hello after 1.5 seconds' after waiting for 1.5 seconds.
const delay = require('delay');
(async () => {
const result = await delay(1500, {value: 'Hello after 1.5 seconds'});
console.log(result);
})();
Delay with Options
This feature supports passing an options object that can include an AbortSignal to cancel the delay. If the abort signal is triggered, the delay is cancelled, and the subsequent code may not execute.
const delay = require('delay');
(async () => {
await delay(1000, {signal: someAbortSignal});
console.log('This will not run if the abort signal is triggered');
})();
Other packages similar to delay
timeout
Similar to 'delay', 'timeout' is used to introduce a delay in asynchronous operations. However, it focuses more on setting timeouts for promises, potentially rejecting them if they take too long, which is a slight functional shift from simply delaying.
sleep-promise
This package offers functionality similar to 'delay' by resolving a promise after a specified timeout. The main difference is in the API design and naming conventions, but the core functionality of introducing delays in promise-based workflows is very similar.
p-timeout
While 'p-timeout' provides delay functionalities, it is primarily designed to add timeout capabilities to promises. It can reject a promise if it does not settle within a specified period, which is a feature not provided by 'delay'.
delay
Delay a promise a specified amount of time
If you target Node.js 16 or later, 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);
baz();
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.
options
Type: object
value
Type: unknown
A value to resolve in the returned promise.
import delay from 'delay';
const result = await delay(100, {value: '🦄'});
console.log(result);
signal
Type: AbortSignal
The returned promise will be rejected with an AbortError
if the signal is aborted.
import delay from 'delay';
const abortController = new AbortController();
setTimeout(() => {
abortController.abort();
}, 500);
try {
await delay(1000, {signal: abortController.signal});
} catch (error) {
console.log(error.name)
}
clearDelay(delayPromise)
Clears the delay and settles the promise.
If you pass in a promise that is already cleared or a promise coming from somewhere else, it does nothing.
import delay, {clearDelay} from 'delay';
const delayedPromise = delay(1000, {value: 'Done'});
setTimeout(() => {
clearDelay(delayedPromise);
}, 500);
console.log(await delayedPromise);
createDelay({clearTimeout, setTimeout})
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: '🦄'});
console.log(result);
Related
- delay-cli - CLI for this module
- p-cancelable - Create a promise that can be canceled
- p-min-delay - Delay a promise a minimum amount of time
- p-immediate - Returns a promise resolved in the next event loop - think
setImmediate()
- p-timeout - Timeout a promise after a specified amount of time
- More…