Timers
自 v0.10.0 版本开始新增
源代码: lib/timers.js
The timer module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
globals, 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 provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.
C Immediate
This object is created internally and is returned from setImmediate(). It
can be passed to clearImmediate() in order to cancel the scheduled
actions.
By default, when an immediate is scheduled, the Node.js event loop will continue
running as long as the immediate is active. The Immediate object returned by
setImmediate() exports both immediate.ref() and immediate.unref()
functions that can be used to control this default behavior.
M immediate.hasRef()
自 v11.0.0 版本开始新增
- Returns:
boolean
If true, the Immediate object will keep the Node.js event loop active.
M immediate.ref()
自 v9.7.0 版本开始新增
- Returns:
Immediatea reference toimmediate
When called, requests that the Node.js event loop not exit so long as the
Immediate is active. Calling immediate.ref() multiple times will have no
effect.
By default, all Immediate objects are "ref'ed", making it normally unnecessary
to call immediate.ref() unless immediate.unref() had been called previously.
M immediate.unref()
自 v9.7.0 版本开始新增
- Returns:
Immediatea reference toimmediate
When called, the active Immediate object will not require the Node.js event
loop to remain active. If there is no other activity keeping the event loop
running, the process may exit before the Immediate object's callback is
invoked. Calling immediate.unref() multiple times will have no effect.
C Timeout
This object is created internally and is returned from setTimeout() and
setInterval(). It can be passed to either clearTimeout() or
clearInterval() in order to cancel the scheduled actions.
By default, when a timer is scheduled using either setTimeout() or
setInterval(), the Node.js event loop will continue running as long as the
timer is active. Each of the Timeout objects returned by these functions
export both timeout.ref() and timeout.unref() functions that can be used to
control this default behavior.
M timeout.close()
自 v0.9.1 版本开始新增
- Returns:
Timeouta reference totimeout
Cancels the timeout.
M timeout.hasRef()
自 v11.0.0 版本开始新增
- Returns:
boolean
If true, the Timeout object will keep the Node.js event loop active.
M timeout.ref()
自 v0.9.1 版本开始新增
- Returns:
Timeouta reference totimeout
When called, requests that the Node.js event loop not exit so long as the
Timeout is active. Calling timeout.ref() multiple times will have no effect.
By default, all Timeout objects are "ref'ed", making it normally unnecessary
to call timeout.ref() unless timeout.unref() had been called previously.
M timeout.refresh()
自 v10.2.0 版本开始新增
- Returns:
Timeouta reference totimeout
Sets the timer's start time to the current time, and reschedules the timer to call its callback at the previously specified duration adjusted to the current time. This is useful for refreshing a timer without allocating a new JavaScript object.
Using this on a timer that has already called its callback will reactivate the timer.
M timeout.unref()
自 v0.9.1 版本开始新增
- Returns:
Timeouta reference totimeout
When called, the active Timeout object will not require the Node.js event loop
to remain active. If there is no other activity keeping the event loop running,
the process may exit before the Timeout object's callback is invoked. Calling
timeout.unref() multiple times will have no effect.
M timeout[Symbol.toPrimitive]()
自 v14.9.0, v12.19.0 版本开始新增
- Returns:
integera number that can be used to reference thistimeout
Coerce a Timeout to a primitive. The primitive can be used to
clear the Timeout. The primitive can only be used in the
same thread where the timeout was created. Therefore, to use it
across worker_threads it must first be passed to the correct
thread. This allows enhanced compatibility with browser
setTimeout() and setInterval() implementations.
Scheduling timers
A timer in Node.js is an internal construct that calls a given function after a certain period of time. When a timer's function is called varies depending on which method was used to create the timer and what other work the Node.js event loop is doing.
M setImmediate(callback[, ...args])
历史
| 版本 | 历史变更 |
|---|---|
| v18.0.0 | Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`. |
| v0.9.1 | 自 v0.9.1 版本开始新增 |
callbackFunctionThe function to call at the end of this turn of the Node.js Event Loop...argsanyOptional arguments to pass when thecallbackis called.- Returns:
Immediatefor use withclearImmediate()
Schedules the "immediate" execution of the callback after I/O events'
callbacks.
When multiple calls to setImmediate() are made, the callback functions are
queued for execution in the order in which they are created. The entire callback
queue is processed every event loop iteration. If an immediate timer is queued
from inside an executing callback, that timer will not be triggered until the
next 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
timersPromises.setImmediate().
M setInterval(callback[, delay[, ...args]])
历史
| 版本 | 历史变更 |
|---|---|
| v18.0.0 | Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`. |
| v0.0.1 | 自 v0.0.1 版本开始新增 |
callbackFunctionThe function to call when the timer elapses.delaynumberThe number of milliseconds to wait before calling thecallback. Default:1....argsanyOptional arguments to pass when thecallbackis called.- Returns:
Timeoutfor use withclearInterval()
Schedules repeated execution of callback every delay milliseconds.
When delay is larger than 2147483647 or less than 1, the delay will 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
timersPromises.setInterval().
M setTimeout(callback[, delay[, ...args]])
历史
| 版本 | 历史变更 |
|---|---|
| v18.0.0 | Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`. |
| v0.0.1 | 自 v0.0.1 版本开始新增 |
callbackFunctionThe function to call when the timer elapses.delaynumberThe number of milliseconds to wait before calling thecallback. Default:1....argsanyOptional arguments to pass when thecallbackis called.- Returns:
Timeoutfor use withclearTimeout()
Schedules execution of a one-time callback after delay milliseconds.
The callback will likely not be invoked in precisely delay 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 the
time specified.
When delay is larger than 2147483647 or less than 1, the delay
will 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
timersPromises.setTimeout().
Cancelling timers
The setImmediate(), setInterval(), and setTimeout() methods
each return objects that represent the scheduled timers. These can be used to
cancel the timer and prevent it from triggering.
For the promisified variants of setImmediate() and setTimeout(),
an AbortController may be used to cancel the timer. When canceled, the
returned Promises will be rejected with an 'AbortError'.
For setImmediate():
JS
For setTimeout():
JS
M clearImmediate(immediate)
自 v0.9.1 版本开始新增
immediateImmediateAnImmediateobject as returned bysetImmediate().
Cancels an Immediate object created by setImmediate().
M clearInterval(timeout)
自 v0.0.1 版本开始新增
timeoutTimeout|string|numberATimeoutobject as returned bysetInterval()or the primitive of theTimeoutobject as a string or a number.
Cancels a Timeout object created by setInterval().
M clearTimeout(timeout)
自 v0.0.1 版本开始新增
timeoutTimeout|string|numberATimeoutobject as returned bysetTimeout()or the primitive of theTimeoutobject as a string or a number.
Cancels a Timeout object created by setTimeout().
Timers Promises API
历史
| 版本 | 历史变更 |
|---|---|
| v16.0.0 | Graduated from experimental. |
| v15.0.0 | 自 v15.0.0 版本开始新增 |
The timers/promises API provides an alternative set of timer functions
that return Promise objects. The API is accessible via
require('node:timers/promises').
MJS
CJS
M timersPromises.setTimeout([delay[, value[, options]]])
自 v15.0.0 版本开始新增
delaynumberThe number of milliseconds to wait before fulfilling the promise. Default:1.valueanyA value with which the promise is fulfilled.optionsObjectrefbooleanSet tofalseto indicate that the scheduledTimeoutshould not require the Node.js event loop to remain active. Default:true.signalAbortSignalAn optionalAbortSignalthat can be used to cancel the scheduledTimeout.
MJS
CJS
M timersPromises.setImmediate([value[, options]])
自 v15.0.0 版本开始新增
valueanyA value with which the promise is fulfilled.optionsObjectrefbooleanSet tofalseto indicate that the scheduledImmediateshould not require the Node.js event loop to remain active. Default:true.signalAbortSignalAn optionalAbortSignalthat can be used to cancel the scheduledImmediate.
MJS
CJS
M timersPromises.setInterval([delay[, value[, options]]])
自 v15.9.0 版本开始新增
Returns an async iterator that generates values in an interval of delay ms.
delaynumberThe number of milliseconds to wait between iterations. Default:1.valueanyA value with which the iterator returns.optionsObjectrefbooleanSet tofalseto indicate that the scheduledTimeoutbetween iterations should not require the Node.js event loop to remain active. Default:true.signalAbortSignalAn optionalAbortSignalthat can be used to cancel the scheduledTimeoutbetween operations.
MJS
CJS
M timersPromises.scheduler.wait(delay[, options])
自 v17.3.0, v16.14.0 版本开始新增
delaynumberThe number of milliseconds to wait before resolving the promise.optionsObjectsignalAbortSignalAn optionalAbortSignalthat can be used to cancel waiting.
- Returns:
Promise
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 calling timersPromises.setTimeout(delay, undefined, options) except that
the ref option is not supported.
MJS
M timersPromises.scheduler.yield()
自 v17.3.0, v16.14.0 版本开始新增
- Returns:
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 calling
timersPromises.setImmediate() with no arguments.