{ "type": "module", "source": "doc/api/timers.md", "modules": [ { "textRaw": "Timers", "name": "timers", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
Source Code: lib/timers.js
\nThe 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.
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.
", "classes": [ { "textRaw": "Class: `Immediate`", "type": "class", "name": "Immediate", "desc": "This object is created internally and is returned from setImmediate()
. It\ncan be passed to clearImmediate()
in order to cancel the scheduled\nactions.
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.
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.
Cancels the immediate. This is similar to calling clearImmediate()
.
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.
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.
Cancels the timeout.
" }, { "textRaw": "`timeout.hasRef()`", "type": "method", "name": "hasRef", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "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.
\nUsing this on a timer that has already called its callback will reactivate the\ntimer.
" }, { "textRaw": "`timeout.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Timeout} a reference to `timeout`", "name": "return", "type": "Timeout", "desc": "a reference to `timeout`" }, "params": [] } ], "desc": "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.
Cancels the timeout.
" } ] } ], "modules": [ { "textRaw": "Scheduling timers", "name": "scheduling_timers", "desc": "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.
", "methods": [ { "textRaw": "`setImmediate(callback[, ...args])`", "type": "method", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Immediate} for use with [`clearImmediate()`][]", "name": "return", "type": "Immediate", "desc": "for use with [`clearImmediate()`][]" }, "params": [ { "textRaw": "`callback` {Function} The function to call at the end of this turn of the Node.js [Event Loop][]", "name": "callback", "type": "Function", "desc": "The function to call at the end of this turn of the Node.js [Event Loop][]" }, { "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", "name": "...args", "type": "any", "desc": "Optional arguments to pass when the `callback` is called." } ] } ], "desc": "Schedules the \"immediate\" execution of the callback
after I/O events'\ncallbacks.
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.
This method has a custom variant for promises that is available using\ntimersPromises.setImmediate()
.
Schedules repeated execution of callback
every delay
milliseconds.
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.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using\ntimersPromises.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.
If callback
is not a function, a TypeError
will be thrown.
This method has a custom variant for promises that is available using\ntimersPromises.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'
.
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.error('The immediate was aborted');\n });\n\nac.abort();\n
\nFor 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.error('The timeout was aborted');\n });\n\nac.abort();\n
",
"methods": [
{
"textRaw": "`clearImmediate(immediate)`",
"type": "method",
"name": "clearImmediate",
"meta": {
"added": [
"v0.9.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`immediate` {Immediate} An `Immediate` object as returned by [`setImmediate()`][].",
"name": "immediate",
"type": "Immediate",
"desc": "An `Immediate` object as returned by [`setImmediate()`][]."
}
]
}
],
"desc": "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')
.
import {\n setTimeout,\n setImmediate,\n setInterval,\n} from 'timers/promises';\n
\nconst {\n setTimeout,\n setImmediate,\n setInterval,\n} = require('node:timers/promises');\n
",
"methods": [
{
"textRaw": "`timersPromises.setTimeout([delay[, value[, options]]])`",
"type": "method",
"name": "setTimeout",
"meta": {
"added": [
"v15.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`delay` {number} The number of milliseconds to wait before fulfilling the promise. **Default:** `1`.",
"name": "delay",
"type": "number",
"default": "`1`",
"desc": "The number of milliseconds to wait before fulfilling the promise."
},
{
"textRaw": "`value` {any} A value with which the promise is fulfilled.",
"name": "value",
"type": "any",
"desc": "A value with which the promise is fulfilled."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`ref` {boolean} Set to `false` to indicate that the scheduled `Timeout` should not require the Node.js event loop to remain active. **Default:** `true`.",
"name": "ref",
"type": "boolean",
"default": "`true`",
"desc": "Set to `false` to indicate that the scheduled `Timeout` should not require the Node.js event loop to remain active."
},
{
"textRaw": "`signal` {AbortSignal} An optional `AbortSignal` that can be used to cancel the scheduled `Timeout`.",
"name": "signal",
"type": "AbortSignal",
"desc": "An optional `AbortSignal` that can be used to cancel the scheduled `Timeout`."
}
]
}
]
}
],
"desc": "import {\n setTimeout,\n} from 'timers/promises';\n\nconst res = await setTimeout(100, 'result');\n\nconsole.log(res); // Prints 'result'\n
\nconst {\n setTimeout,\n} = require('node:timers/promises');\n\nsetTimeout(100, 'result').then((res) => {\n console.log(res); // Prints 'result'\n});\n
"
},
{
"textRaw": "`timersPromises.setImmediate([value[, options]])`",
"type": "method",
"name": "setImmediate",
"meta": {
"added": [
"v15.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} A value with which the promise is fulfilled.",
"name": "value",
"type": "any",
"desc": "A value with which the promise is fulfilled."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`ref` {boolean} Set to `false` to indicate that the scheduled `Immediate` should not require the Node.js event loop to remain active. **Default:** `true`.",
"name": "ref",
"type": "boolean",
"default": "`true`",
"desc": "Set to `false` to indicate that the scheduled `Immediate` should not require the Node.js event loop to remain active."
},
{
"textRaw": "`signal` {AbortSignal} An optional `AbortSignal` that can be used to cancel the scheduled `Immediate`.",
"name": "signal",
"type": "AbortSignal",
"desc": "An optional `AbortSignal` that can be used to cancel the scheduled `Immediate`."
}
]
}
]
}
],
"desc": "import {\n setImmediate,\n} from 'timers/promises';\n\nconst res = await setImmediate('result');\n\nconsole.log(res); // Prints 'result'\n
\nconst {\n setImmediate,\n} = require('node:timers/promises');\n\nsetImmediate('result').then((res) => {\n console.log(res); // Prints 'result'\n});\n
"
},
{
"textRaw": "`timersPromises.setInterval([delay[, value[, options]]])`",
"type": "method",
"name": "setInterval",
"meta": {
"added": [
"v15.9.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Returns an async iterator that generates values in an interval of delay
ms.\nIf ref
is true
, you need to call next()
of async iterator explicitly\nor implicitly to keep the event loop alive.
delay
<number> The number of milliseconds to wait between iterations.\nDefault: 1
.value
<any> A value with which the iterator returns.options
<Object>\nref
<boolean> Set to false
to indicate that the scheduled Timeout
\nbetween iterations should not require the Node.js event loop to\nremain active.\nDefault: true
.signal
<AbortSignal> An optional AbortSignal
that can be used to\ncancel the scheduled Timeout
between operations.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
\nconst {\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
"
},
{
"textRaw": "`timersPromises.scheduler.wait(delay[, options])`",
"type": "method",
"name": "wait",
"meta": {
"added": [
"v17.3.0",
"v16.14.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"return": {
"textRaw": "Returns: {Promise}",
"name": "return",
"type": "Promise"
},
"params": [
{
"textRaw": "`delay` {number} The number of milliseconds to wait before resolving the promise.",
"name": "delay",
"type": "number",
"desc": "The number of milliseconds to wait before resolving the promise."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} An optional `AbortSignal` that can be used to cancel waiting.",
"name": "signal",
"type": "AbortSignal",
"desc": "An optional `AbortSignal` that can be used to cancel waiting."
}
]
}
]
}
],
"desc": "An experimental API defined by the Scheduling APIs draft specification\nbeing developed as a standard Web Platform API.
\nCalling timersPromises.scheduler.wait(delay, options)
is roughly equivalent\nto calling timersPromises.setTimeout(delay, undefined, options)
except that\nthe ref
option is not supported.
import { scheduler } from 'node:timers/promises';\n\nawait scheduler.wait(1000); // Wait one second before continuing\n
"
},
{
"textRaw": "`timersPromises.scheduler.yield()`",
"type": "method",
"name": "yield",
"meta": {
"added": [
"v17.3.0",
"v16.14.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"return": {
"textRaw": "Returns: {Promise}",
"name": "return",
"type": "Promise"
},
"params": []
}
],
"desc": "An experimental API defined by the Scheduling APIs draft specification\nbeing developed as a standard Web Platform API.
\nCalling timersPromises.scheduler.yield()
is equivalent to calling\ntimersPromises.setImmediate()
with no arguments.