Source Code: lib/timers.js
The timer module exposes a global API for scheduling functions to\nbe called at some future period of time. Because the timer functions are\nglobals, there is no need to call require('node:timers') to use the API.
timer
require('node:timers')
The timer functions within Node.js implement a similar API as the timers API\nprovided by Web Browsers but use a different internal implementation that is\nbuilt around the Node.js Event Loop.
This object is created internally and is returned from setImmediate(). It\ncan be passed to clearImmediate() in order to cancel the scheduled\nactions.
setImmediate()
clearImmediate()
By default, when an immediate is scheduled, the Node.js event loop will continue\nrunning as long as the immediate is active. The Immediate object returned by\nsetImmediate() exports both immediate.ref() and immediate.unref()\nfunctions that can be used to control this default behavior.
Immediate
immediate.ref()
immediate.unref()
If true, the Immediate object will keep the Node.js event loop active.
When called, requests that the Node.js event loop not exit so long as the\nImmediate is active. Calling immediate.ref() multiple times will have no\neffect.
By default, all Immediate objects are \"ref'ed\", making it normally unnecessary\nto call immediate.ref() unless immediate.unref() had been called previously.
When called, the active Immediate object will not require the Node.js event\nloop to remain active. If there is no other activity keeping the event loop\nrunning, the process may exit before the Immediate object's callback is\ninvoked. Calling immediate.unref() multiple times will have no effect.
This object is created internally and is returned from setTimeout() and\nsetInterval(). It can be passed to either clearTimeout() or\nclearInterval() in order to cancel the scheduled actions.
setTimeout()
setInterval()
clearTimeout()
clearInterval()
By default, when a timer is scheduled using either setTimeout() or\nsetInterval(), the Node.js event loop will continue running as long as the\ntimer is active. Each of the Timeout objects returned by these functions\nexport both timeout.ref() and timeout.unref() functions that can be used to\ncontrol this default behavior.
Timeout
timeout.ref()
timeout.unref()
Cancels the timeout.
If true, the Timeout object will keep the Node.js event loop active.
When called, requests that the Node.js event loop not exit so long as the\nTimeout is active. Calling timeout.ref() multiple times will have no effect.
By default, all Timeout objects are \"ref'ed\", making it normally unnecessary\nto call timeout.ref() unless timeout.unref() had been called previously.
Sets the timer's start time to the current time, and reschedules the timer to\ncall its callback at the previously specified duration adjusted to the current\ntime. This is useful for refreshing a timer without allocating a new\nJavaScript object.
Using this on a timer that has already called its callback will reactivate the\ntimer.
When called, the active Timeout object will not require the Node.js event loop\nto remain active. If there is no other activity keeping the event loop running,\nthe process may exit before the Timeout object's callback is invoked. Calling\ntimeout.unref() multiple times will have no effect.
Coerce a Timeout to a primitive. The primitive can be used to\nclear the Timeout. The primitive can only be used in the\nsame thread where the timeout was created. Therefore, to use it\nacross worker_threads it must first be passed to the correct\nthread. This allows enhanced compatibility with browser\nsetTimeout() and setInterval() implementations.
worker_threads
A timer in Node.js is an internal construct that calls a given function after\na certain period of time. When a timer's function is called varies depending on\nwhich method was used to create the timer and what other work the Node.js\nevent loop is doing.
Schedules the \"immediate\" execution of the callback after I/O events'\ncallbacks.
callback
When multiple calls to setImmediate() are made, the callback functions are\nqueued for execution in the order in which they are created. The entire callback\nqueue is processed every event loop iteration. If an immediate timer is queued\nfrom inside an executing callback, that timer will not be triggered until the\nnext event loop iteration.
If callback is not a function, a TypeError will be thrown.
TypeError
This method has a custom variant for promises that is available using\ntimersPromises.setImmediate().
timersPromises.setImmediate()
Schedules repeated execution of callback every delay milliseconds.
delay
When delay is larger than 2147483647 or less than 1, the delay will be\nset to 1. Non-integer delays are truncated to an integer.
2147483647
1
This method has a custom variant for promises that is available using\ntimersPromises.setInterval().
timersPromises.setInterval()
Schedules execution of a one-time callback after delay milliseconds.
The callback will likely not be invoked in precisely delay milliseconds.\nNode.js makes no guarantees about the exact timing of when callbacks will fire,\nnor of their ordering. The callback will be called as close as possible to the\ntime specified.
When delay is larger than 2147483647 or less than 1, the delay\nwill be set to 1. Non-integer delays are truncated to an integer.
This method has a custom variant for promises that is available using\ntimersPromises.setTimeout().
timersPromises.setTimeout()
The setImmediate(), setInterval(), and setTimeout() methods\neach return objects that represent the scheduled timers. These can be used to\ncancel the timer and prevent it from triggering.
For the promisified variants of setImmediate() and setTimeout(),\nan AbortController may be used to cancel the timer. When canceled, the\nreturned Promises will be rejected with an 'AbortError'.
AbortController
'AbortError'
For setImmediate():
const { setImmediate: setImmediatePromise } = require('node:timers/promises');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nsetImmediatePromise('foobar', { signal })\n .then(console.log)\n .catch((err) => {\n if (err.name === 'AbortError')\n console.log('The immediate was aborted');\n });\n\nac.abort();\n
For setTimeout():
const { setTimeout: setTimeoutPromise } = require('node:timers/promises');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nsetTimeoutPromise(1000, 'foobar', { signal })\n .then(console.log)\n .catch((err) => {\n if (err.name === 'AbortError')\n console.log('The timeout was aborted');\n });\n\nac.abort();\n
Cancels an Immediate object created by setImmediate().
Cancels a Timeout object created by setInterval().
Cancels a Timeout object created by setTimeout().
The timers/promises API provides an alternative set of timer functions\nthat return Promise objects. The API is accessible via\nrequire('node:timers/promises').
timers/promises
Promise
require('node:timers/promises')
import {\n setTimeout,\n setImmediate,\n setInterval,\n} from 'timers/promises';\n
const {\n setTimeout,\n setImmediate,\n setInterval,\n} = require('node:timers/promises');\n
import {\n setTimeout,\n} from 'timers/promises';\n\nconst res = await setTimeout(100, 'result');\n\nconsole.log(res); // Prints 'result'\n
const {\n setTimeout,\n} = require('node:timers/promises');\n\nsetTimeout(100, 'result').then((res) => {\n console.log(res); // Prints 'result'\n});\n
import {\n setImmediate,\n} from 'timers/promises';\n\nconst res = await setImmediate('result');\n\nconsole.log(res); // Prints 'result'\n
const {\n setImmediate,\n} = require('node:timers/promises');\n\nsetImmediate('result').then((res) => {\n console.log(res); // Prints 'result'\n});\n
Returns an async iterator that generates values in an interval of delay ms.
value
options
ref
false
true
signal
AbortSignal
import {\n setInterval,\n} from 'timers/promises';\n\nconst interval = 100;\nfor await (const startTime of setInterval(interval, Date.now())) {\n const now = Date.now();\n console.log(now);\n if ((now - startTime) > 1000)\n break;\n}\nconsole.log(Date.now());\n
const {\n setInterval,\n} = require('node:timers/promises');\nconst interval = 100;\n\n(async function() {\n for await (const startTime of setInterval(interval, Date.now())) {\n const now = Date.now();\n console.log(now);\n if ((now - startTime) > 1000)\n break;\n }\n console.log(Date.now());\n})();\n
An experimental API defined by the Scheduling APIs draft specification\nbeing developed as a standard Web Platform API.
Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent\nto calling timersPromises.setTimeout(delay, undefined, options) except that\nthe ref option is not supported.
timersPromises.scheduler.wait(delay, options)
timersPromises.setTimeout(delay, undefined, options)
import { scheduler } from 'node:timers/promises';\n\nawait scheduler.wait(1000); // Wait one second before continuing\n
Calling timersPromises.scheduler.yield() is equivalent to calling\ntimersPromises.setImmediate() with no arguments.
timersPromises.scheduler.yield()