Timers#
Source Code:lib/timers.js
Thetimer module exposes a global API for scheduling functions tobe called at some future period of time. Because the timer functions areglobals, there is no need to callrequire('node:timers') to use the API.
The timer functions within Node.js implement a similar API as the timers APIprovided by Web Browsers but use a different internal implementation that isbuilt around the Node.jsEvent Loop.
Class:Immediate#
This object is created internally and is returned fromsetImmediate(). Itcan be passed toclearImmediate() in order to cancel the scheduledactions.
By default, when an immediate is scheduled, the Node.js event loop will continuerunning as long as the immediate is active. TheImmediate object returned bysetImmediate() exports bothimmediate.ref() andimmediate.unref()functions that can be used to control this default behavior.
immediate.hasRef()#
- Returns:<boolean>
If true, theImmediate object will keep the Node.js event loop active.
immediate.ref()#
- Returns:<Immediate> a reference to
immediate
When called, requests that the Node.js event loopnot exit so long as theImmediate is active. Callingimmediate.ref() multiple times will have noeffect.
By default, allImmediate objects are "ref'ed", making it normally unnecessaryto callimmediate.ref() unlessimmediate.unref() had been called previously.
immediate.unref()#
- Returns:<Immediate> a reference to
immediate
When called, the activeImmediate object will not require the Node.js eventloop to remain active. If there is no other activity keeping the event looprunning, the process may exit before theImmediate object's callback isinvoked. Callingimmediate.unref() multiple times will have no effect.
immediate[Symbol.dispose]()#
History
| Version | Changes |
|---|---|
| v24.2.0 | No longer experimental. |
| v20.5.0, v18.18.0 | Added in: v20.5.0, v18.18.0 |
Cancels the immediate. This is similar to callingclearImmediate().
Class:Timeout#
This object is created internally and is returned fromsetTimeout() andsetInterval(). It can be passed to eitherclearTimeout() orclearInterval() in order to cancel the scheduled actions.
By default, when a timer is scheduled using eithersetTimeout() orsetInterval(), the Node.js event loop will continue running as long as thetimer is active. Each of theTimeout objects returned by these functionsexport bothtimeout.ref() andtimeout.unref() functions that can be used tocontrol this default behavior.
timeout.close()#
clearTimeout() instead.- Returns:<Timeout> a reference to
timeout
Cancels the timeout.
timeout.hasRef()#
- Returns:<boolean>
If true, theTimeout object will keep the Node.js event loop active.
timeout.ref()#
- Returns:<Timeout> a reference to
timeout
When called, requests that the Node.js event loopnot exit so long as theTimeout is active. Callingtimeout.ref() multiple times will have no effect.
By default, allTimeout objects are "ref'ed", making it normally unnecessaryto calltimeout.ref() unlesstimeout.unref() had been called previously.
timeout.refresh()#
- Returns:<Timeout> a reference to
timeout
Sets the timer's start time to the current time, and reschedules the timer tocall its callback at the previously specified duration adjusted to the currenttime. This is useful for refreshing a timer without allocating a newJavaScript object.
Using this on a timer that has already called its callback will reactivate thetimer.
timeout.unref()#
- Returns:<Timeout> a reference to
timeout
When called, the activeTimeout object will not require the Node.js event loopto remain active. If there is no other activity keeping the event loop running,the process may exit before theTimeout object's callback is invoked. Callingtimeout.unref() multiple times will have no effect.
timeout[Symbol.toPrimitive]()#
- Returns:<integer> a number that can be used to reference this
timeout
Coerce aTimeout to a primitive. The primitive can be used toclear theTimeout. The primitive can only be used in thesame thread where the timeout was created. Therefore, to use itacrossworker_threads it must first be passed to the correctthread. This allows enhanced compatibility with browsersetTimeout() andsetInterval() implementations.
timeout[Symbol.dispose]()#
History
| Version | Changes |
|---|---|
| v24.2.0 | No longer experimental. |
| v20.5.0, v18.18.0 | Added in: v20.5.0, v18.18.0 |
Cancels the timeout.
Scheduling timers#
A timer in Node.js is an internal construct that calls a given function aftera certain period of time. When a timer's function is called varies depending onwhich method was used to create the timer and what other work the Node.jsevent loop is doing.
setImmediate(callback[, ...args])#
History
| Version | Changes |
|---|---|
| v18.0.0 | Passing an invalid callback to the |
| v0.9.1 | Added in: v0.9.1 |
callback<Function> The function to call at the end of this turn ofthe Node.jsEvent Loop...args<any> Optional arguments to pass when thecallbackis called.- Returns:<Immediate> for use with
clearImmediate()
Schedules the "immediate" execution of thecallback after I/O events'callbacks.
When multiple calls tosetImmediate() are made, thecallback functions arequeued for execution in the order in which they are created. The entire callbackqueue is processed every event loop iteration. If an immediate timer is queuedfrom inside an executing callback, that timer will not be triggered until thenext event loop iteration.
Ifcallback is not a function, aTypeError will be thrown.
This method has a custom variant for promises that is available usingtimersPromises.setImmediate().
setInterval(callback[, delay[, ...args]])#
History
| Version | Changes |
|---|---|
| v18.0.0 | Passing an invalid callback to the |
| v0.0.1 | Added in: v0.0.1 |
callback<Function> The function to call when the timer elapses.delay<number> The number of milliseconds to wait before calling thecallback.Default:1....args<any> Optional arguments to pass when thecallbackis called.- Returns:<Timeout> for use with
clearInterval()
Schedules repeated execution ofcallback everydelay milliseconds.
Whendelay is larger than2147483647 or less than1 orNaN, thedelaywill be set to1. Non-integer delays are truncated to an integer.
Ifcallback is not a function, aTypeError will be thrown.
This method has a custom variant for promises that is available usingtimersPromises.setInterval().
setTimeout(callback[, delay[, ...args]])#
History
| Version | Changes |
|---|---|
| v18.0.0 | Passing an invalid callback to the |
| v0.0.1 | Added in: v0.0.1 |
callback<Function> The function to call when the timer elapses.delay<number> The number of milliseconds to wait before calling thecallback.Default:1....args<any> Optional arguments to pass when thecallbackis called.- Returns:<Timeout> for use with
clearTimeout()
Schedules execution of a one-timecallback afterdelay milliseconds.
Thecallback will likely not be invoked in preciselydelay milliseconds.Node.js makes no guarantees about the exact timing of when callbacks will fire,nor of their ordering. The callback will be called as close as possible to thetime specified.
Whendelay is larger than2147483647 or less than1 orNaN, thedelaywill be set to1. Non-integer delays are truncated to an integer.
Ifcallback is not a function, aTypeError will be thrown.
This method has a custom variant for promises that is available usingtimersPromises.setTimeout().
Cancelling timers#
ThesetImmediate(),setInterval(), andsetTimeout() methodseach return objects that represent the scheduled timers. These can be used tocancel the timer and prevent it from triggering.
For the promisified variants ofsetImmediate() andsetTimeout(),anAbortController may be used to cancel the timer. When canceled, thereturned Promises will be rejected with an'AbortError'.
ForsetImmediate():
import { setImmediateas setImmediatePromise }from'node:timers/promises';const ac =newAbortController();const signal = ac.signal;// We do not `await` the promise so `ac.abort()` is called concurrently.setImmediatePromise('foobar', { signal }) .then(console.log) .catch((err) => {if (err.name ==='AbortError')console.error('The immediate was aborted'); });ac.abort();const {setImmediate: setImmediatePromise } =require('node:timers/promises');const ac =newAbortController();const signal = ac.signal;setImmediatePromise('foobar', { signal }) .then(console.log) .catch((err) => {if (err.name ==='AbortError')console.error('The immediate was aborted'); });ac.abort();
ForsetTimeout():
import {setTimeoutas setTimeoutPromise }from'node:timers/promises';const ac =newAbortController();const signal = ac.signal;// We do not `await` the promise so `ac.abort()` is called concurrently.setTimeoutPromise(1000,'foobar', { signal }) .then(console.log) .catch((err) => {if (err.name ==='AbortError')console.error('The timeout was aborted'); });ac.abort();const {setTimeout: setTimeoutPromise } =require('node:timers/promises');const ac =newAbortController();const signal = ac.signal;setTimeoutPromise(1000,'foobar', { signal }) .then(console.log) .catch((err) => {if (err.name ==='AbortError')console.error('The timeout was aborted'); });ac.abort();
clearImmediate(immediate)#
immediate<Immediate> AnImmediateobject as returned bysetImmediate().
Cancels anImmediate object created bysetImmediate().
clearInterval(timeout)#
timeout<Timeout> |<string> |<number> ATimeoutobject as returned bysetInterval()or theprimitive of theTimeoutobject as a string or a number.
Cancels aTimeout object created bysetInterval().
clearTimeout(timeout)#
timeout<Timeout> |<string> |<number> ATimeoutobject as returned bysetTimeout()or theprimitive of theTimeoutobject as a string or a number.
Cancels aTimeout object created bysetTimeout().
Timers Promises API#
History
| Version | Changes |
|---|---|
| v16.0.0 | Graduated from experimental. |
| v15.0.0 | Added in: v15.0.0 |
Thetimers/promises API provides an alternative set of timer functionsthat returnPromise objects. The API is accessible viarequire('node:timers/promises').
import {setTimeout, setImmediate,setInterval,}from'node:timers/promises';const {setTimeout, setImmediate,setInterval,} =require('node:timers/promises');
timersPromises.setTimeout([delay[, value[, options]]])#
delay<number> The number of milliseconds to wait before fulfilling thepromise.Default:1.value<any> A value with which the promise is fulfilled.options<Object>ref<boolean> Set tofalseto indicate that the scheduledTimeoutshould not require the Node.js event loop to remain active.Default:true.signal<AbortSignal> An optionalAbortSignalthat can be used tocancel the scheduledTimeout.
import {setTimeout,}from'node:timers/promises';const res =awaitsetTimeout(100,'result');console.log(res);// Prints 'result'const {setTimeout,} =require('node:timers/promises');setTimeout(100,'result').then((res) => {console.log(res);// Prints 'result'});
timersPromises.setImmediate([value[, options]])#
value<any> A value with which the promise is fulfilled.options<Object>ref<boolean> Set tofalseto indicate that the scheduledImmediateshould not require the Node.js event loop to remain active.Default:true.signal<AbortSignal> An optionalAbortSignalthat can be used tocancel the scheduledImmediate.
import { setImmediate,}from'node:timers/promises';const res =awaitsetImmediate('result');console.log(res);// Prints 'result'const { setImmediate,} =require('node:timers/promises');setImmediate('result').then((res) => {console.log(res);// Prints 'result'});
timersPromises.setInterval([delay[, value[, options]]])#
Returns an async iterator that generates values in an interval ofdelay ms.Ifref istrue, you need to callnext() of async iterator explicitlyor implicitly to keep the event loop alive.
delay<number> The number of milliseconds to wait between iterations.Default:1.value<any> A value with which the iterator returns.options<Object>ref<boolean> Set tofalseto indicate that the scheduledTimeoutbetween iterations should not require the Node.js event loop toremain active.Default:true.signal<AbortSignal> An optionalAbortSignalthat can be used tocancel the scheduledTimeoutbetween operations.
import {setInterval,}from'node:timers/promises';const interval =100;forawait (const startTimeofsetInterval(interval,Date.now())) {const now =Date.now();console.log(now);if ((now - startTime) >1000)break;}console.log(Date.now());const {setInterval,} =require('node:timers/promises');const interval =100;(asyncfunction() {forawait (const startTimeofsetInterval(interval,Date.now())) {const now =Date.now();console.log(now);if ((now - startTime) >1000)break; }console.log(Date.now());})();
timersPromises.scheduler.wait(delay[, options])#
delay<number> The number of milliseconds to wait before resolving thepromise.options<Object>ref<boolean> Set tofalseto indicate that the scheduledTimeoutshould not require the Node.js event loop to remain active.Default:true.signal<AbortSignal> An optionalAbortSignalthat can be used tocancel waiting.
- Returns:<Promise>
An experimental API defined by theScheduling APIs draft specificationbeing developed as a standard Web Platform API.
CallingtimersPromises.scheduler.wait(delay, options) is equivalentto callingtimersPromises.setTimeout(delay, undefined, options).
import { scheduler }from'node:timers/promises';await scheduler.wait(1000);// Wait one second before continuingtimersPromises.scheduler.yield()#
- Returns:<Promise>
An experimental API defined by theScheduling APIs draft specificationbeing developed as a standard Web Platform API.
CallingtimersPromises.scheduler.yield() is equivalent to callingtimersPromises.setImmediate() with no arguments.