import {
setImmediate,
} from 'node:timers/promises';
const res = await setImmediate('result');
console.log(res); // Prints 'result'
Node.js module
timers/promises
The 'node:timers/promises'
submodule provides Promise-based timer functions such as setTimeout
and setImmediate
, enabling async/await syntax for delayed execution.
It simplifies scheduling and timing of asynchronous code in modern JavaScript.
- value?: T,): Promise<T>;@param value
A value with which the promise is fulfilled.
- delay?: number,value?: T,): AsyncIterator<T>;
Returns an async iterator that generates values in an interval of
delay
ms. Ifref
istrue
, you need to callnext()
of async iterator explicitly or implicitly to keep the event loop alive.import { setInterval, } from 'node:timers/promises'; const interval = 100; for await (const startTime of setInterval(interval, Date.now())) { const now = Date.now(); console.log(now); if ((now - startTime) > 1000) break; } console.log(Date.now());
@param delayThe number of milliseconds to wait between iterations. Default:
1
.@param valueA value with which the iterator returns.
- delay?: number,value?: T,): Promise<T>;
import { setTimeout, } from 'node:timers/promises'; const res = await setTimeout(100, 'result'); console.log(res); // Prints 'result'
@param delayThe number of milliseconds to wait before fulfilling the promise. Default:
1
.@param valueA value with which the promise is fulfilled.
Type definitions
interface Scheduler
- wait(delay: number,): Promise<void>;
An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API.
Calling
timersPromises.scheduler.wait(delay, options)
is roughly equivalent to callingtimersPromises.setTimeout(delay, undefined, options)
except that theref
option is not supported.import { scheduler } from 'node:timers/promises'; await scheduler.wait(1000); // Wait one second before continuing
@param delayThe number of milliseconds to wait before resolving the promise.
An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API.
Calling
timersPromises.scheduler.yield()
is equivalent to callingtimersPromises.setImmediate()
with no arguments.