delay
Delay a promise a specified amount of time
Install
$ npm install delay
Usage
const delay = ; async { ; await ; // Executed 100 milliseconds later ;};
API
delay(milliseconds, [options])
Create a promise which resolves after the specified milliseconds
.
delay.reject(milliseconds, [options])
Create a promise which rejects after the specified milliseconds
.
milliseconds
Type: number
Milliseconds to delay the promise.
options
Type: Object
value
Type: any
Optional value to resolve or reject in the returned promise.
signal
Type: AbortSignal
The returned promise will be rejected with an AbortError if the signal is aborted. AbortSignal is available in all modern browsers and there is a ponyfill for Node.js.
delayPromise.clear()
Clears the delay and settles the promise.
delay.createWithTimers({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.
Advanced usage
Passing a value:
const delay = ; async const result = await ; // Executed after 100 milliseconds console; //=> '🦄';
Using delay.reject()
, which optionally accepts a value and rejects it ms
later:
const delay = ; async { try await delay; console; catch error // 100 milliseconds later console; //=> [Error: 🦄] };
You can settle the delay early by calling .clear()
:
const delay = ; async { const delayedPromise = ; ; // 500 milliseconds later console; //=> 'Done'};
You can abort the delay with an AbortSignal:
const delay = ; async { const abortController = ; ; try await ; catch error // 500 milliseconds later console //=> 'AbortError' };
Create a new instance that is unaffected by libraries such as lolex:
const delay = ; const customDelay = delay; async const result = await ; // Executed after 100 milliseconds console; //=> '🦄';
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…
License
MIT © Sindre Sorhus