- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
Node.js v22.11.0 文档
- Node.js v22.11.0
- 目录
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- 其他版本
定时器#
¥Timers
¥Stability: 2 - Stable
源代码: lib/timers.js
timer
模块暴露了一个全局的用于在未来某个时间点调用的调度函数的 API。因为定时器函数是全局的,所以不需要调用 require('node:timers')
来使用该 API。
¥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.
Node.js 中的定时器函数实现了与 Web 浏览器提供的定时器 API 类似的 API,但使用了围绕 Node.js 事件循环 构建的不同内部实现。
¥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.
类:Immediate
#
¥Class: Immediate
此对象是在 setImmediate()
内部创建并返回。它可以传给 clearImmediate()
以取消调度的行动。
¥This object is created internally and is returned from setImmediate()
. It
can be passed to clearImmediate()
in order to cancel the scheduled
actions.
默认情况下,当立即调度时,只要立即处于活动状态,则 Node.js 事件循环就会继续运行。setImmediate()
返回的 Immediate
对象导出可用于控制此默认行为的 immediate.ref()
和 immediate.unref()
函数。
¥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.
immediate.hasRef()
#
如果为 true,则 Immediate
对象将使 Node.js 事件循环保持活动状态。
¥If true, the Immediate
object will keep the Node.js event loop active.
immediate.ref()
#
-
返回:<Immediate> 参考
immediate
¥Returns: <Immediate> a reference to
immediate
调用时,请求只要 Immediate
处于活动状态,Node.js 事件循环就不会退出。多次调用 immediate.ref()
将不起作用。
¥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.
默认情况下,所有 Immediate
对象都是 "引用的",因此通常无需调用 immediate.ref()
,除非之前已调用 immediate.unref()
。
¥By default, all Immediate
objects are "ref'ed", making it normally unnecessary
to call immediate.ref()
unless immediate.unref()
had been called previously.
immediate.unref()
#
-
返回:<Immediate> 参考
immediate
¥Returns: <Immediate> a reference to
immediate
调用时,活动的 Immediate
对象不需要 Node.js 事件循环保持活动状态。如果没有其他活动保持事件循环运行,则进程可能会在调用 Immediate
对象的回调之前退出。多次调用 immediate.unref()
将不起作用。
¥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.
immediate[Symbol.dispose]()
#
¥Stability: 1 - Experimental
取消即时。这与调用 clearImmediate()
类似。
¥Cancels the immediate. This is similar to calling clearImmediate()
.
类:Timeout
#
¥Class: Timeout
此对象是在 setTimeout()
和 setInterval()
内部创建并返回。它可以传给 clearTimeout()
或 clearInterval()
以取消调度的行动。
¥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.
默认情况下,当使用 setTimeout()
或 setInterval()
调度定时器时,只要定时器处于活动状态,则 Node.js 事件循环就会继续运行。这些函数返回的每个 Timeout
对象都导出可用于控制此默认行为的 timeout.ref()
和 timeout.unref()
函数。
¥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.
timeout.close()
#
取消超时。
¥Cancels the timeout.
timeout.hasRef()
#
如果为 true,则 Timeout
对象将使 Node.js 事件循环保持活动状态。
¥If true, the Timeout
object will keep the Node.js event loop active.
timeout.ref()
#
调用时,请求只要 Timeout
处于活动状态,Node.js 事件循环就不会退出。多次调用 timeout.ref()
将不起作用。
¥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.
默认情况下,所有 Timeout
对象都是 "引用的",因此通常无需调用 timeout.ref()
,除非之前已调用 timeout.unref()
。
¥By default, all Timeout
objects are "ref'ed", making it normally unnecessary
to call timeout.ref()
unless timeout.unref()
had been called previously.
timeout.refresh()
#
将定时器的开始时间设置为当前时间,并重新调度定时器在调整为当前时间的先前指定的时长调用其回调。这对于在不分配新的 JavaScript 对象的情况下刷新定时器很有用。
¥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.
timeout.unref()
#
调用时,活动的 Timeout
对象不需要 Node.js 事件循环保持活动状态。如果没有其他活动保持事件循环运行,则进程可能会在调用 Timeout
对象的回调之前退出。多次调用 timeout.unref()
将不起作用。
¥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.
timeout[Symbol.toPrimitive]()
#
-
返回:<integer> 可用于引用此
timeout
的数字¥Returns: <integer> a number that can be used to reference this
timeout
将 Timeout
强制为原始类型。该原始类型可用于清除 Timeout
。该原始类型只能在创建超时的同一线程中使用。因此,要在 worker_threads
上使用它,则必须首先将其传给正确的线程。这允许增强与浏览器 setTimeout()
和 setInterval()
实现的兼容性。
¥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.
timeout[Symbol.dispose]()
#
¥Stability: 1 - Experimental
取消超时。
¥Cancels the timeout.
调度定时器#
¥Scheduling timers
Node.js 中的定时器是一种会在一段时间后调用给定函数的内部构造。定时器函数的调用时间取决于用于创建定时器的方法以及 Node.js 事件循环正在执行的其他工作。
¥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.
setImmediate(callback[, ...args])
#
-
callback
<Function> 本轮 Node.js 事件循环 结束时调用的函数¥
callback
<Function> The function to call at the end of this turn of the Node.js Event Loop -
...args
<any> 调用callback
时要传入的可选参数。¥
...args
<any> Optional arguments to pass when thecallback
is called. -
返回:<Immediate> 与
clearImmediate()
配合使用¥Returns: <Immediate> for use with
clearImmediate()
在 I/O 事件回调后安排 callback
的 "immediate" 执行。
¥Schedules the "immediate" execution of the callback
after I/O events'
callbacks.
当多次调用 setImmediate()
时,则 callback
函数会按照它们的创建顺序排队执行。每次事件循环迭代都会处理整个回调队列。如果立即定时器从正在执行的回调中排队,则直到下一次事件循环迭代才会触发该定时器。
¥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.
如果 callback
不是函数,则将抛出 TypeError
。
¥If callback
is not a function, a TypeError
will be thrown.
此方法具有可使用 timersPromises.setImmediate()
获得的 promise 的自定义变体。
¥This method has a custom variant for promises that is available using
timersPromises.setImmediate()
.
setInterval(callback[, delay[, ...args]])
#
-
callback
<Function> 当定时器结束时调用的函数。¥
callback
<Function> The function to call when the timer elapses. -
delay
<number> 调用callback
之前等待的毫秒数。默认值:1
。¥
delay
<number> The number of milliseconds to wait before calling thecallback
. Default:1
. -
...args
<any> 调用callback
时要传入的可选参数。¥
...args
<any> Optional arguments to pass when thecallback
is called. -
返回:<Timeout> 与
clearInterval()
配合使用¥Returns: <Timeout> for use with
clearInterval()
每 delay
毫秒调度重复执行 callback
。
¥Schedules repeated execution of callback
every delay
milliseconds.
当 delay
大于 2147483647
或小于 1
时,则 delay
将设置为 1
。非整数延迟被截断为整数。
¥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.
如果 callback
不是函数,则将抛出 TypeError
。
¥If callback
is not a function, a TypeError
will be thrown.
此方法具有可使用 timersPromises.setInterval()
获得的 promise 的自定义变体。
¥This method has a custom variant for promises that is available using
timersPromises.setInterval()
.
setTimeout(callback[, delay[, ...args]])
#
-
callback
<Function> 当定时器结束时调用的函数。¥
callback
<Function> The function to call when the timer elapses. -
delay
<number> 调用callback
之前等待的毫秒数。默认值:1
。¥
delay
<number> The number of milliseconds to wait before calling thecallback
. Default:1
. -
...args
<any> 调用callback
时要传入的可选参数。¥
...args
<any> Optional arguments to pass when thecallback
is called. -
返回:<Timeout> 与
clearTimeout()
配合使用¥Returns: <Timeout> for use with
clearTimeout()
在 delay
毫秒后调度单次的 callback
的执行。
¥Schedules execution of a one-time callback
after delay
milliseconds.
callback
可能不会在精确的 delay
毫秒内被调用。Node.js 不保证回调将触发的确切时间,也不保证它们的顺序。回调将在尽可能接近指定的时间时调用。
¥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.
当 delay
大于 2147483647
或小于 1
时,则 delay
将设置为 1
。非整数延迟被截断为整数。
¥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.
如果 callback
不是函数,则将抛出 TypeError
。
¥If callback
is not a function, a TypeError
will be thrown.
此方法具有可使用 timersPromises.setTimeout()
获得的 promise 的自定义变体。
¥This method has a custom variant for promises that is available using
timersPromises.setTimeout()
.
取消定时器#
¥Cancelling timers
setImmediate()
、setInterval()
和 setTimeout()
方法各自返回表示调度的定时器的对象。这些可用于取消定时器并防止其触发。
¥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.
对于 setImmediate()
和 setTimeout()
的 promise 化变体,可以使用 AbortController
来取消定时器。当取消时,返回的 Promise 将使用 'AbortError'
拒绝。
¥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'
.
对于 setImmediate()
:
¥For setImmediate()
:
const { setImmediate: setImmediatePromise } = require('node:timers/promises');
const ac = new AbortController();
const signal = ac.signal;
setImmediatePromise('foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.name === 'AbortError')
console.error('The immediate was aborted');
});
ac.abort();
对于 setTimeout()
:
¥For setTimeout()
:
const { setTimeout: setTimeoutPromise } = require('node:timers/promises');
const ac = new AbortController();
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>setImmediate()
返回的Immediate
对象。¥
immediate
<Immediate> AnImmediate
object as returned bysetImmediate()
.
取消由 setImmediate()
创建的 Immediate
对象。
¥Cancels an Immediate
object created by setImmediate()
.
clearInterval(timeout)
#
-
timeout
<Timeout> | <string> | <number> 由setInterval()
或Timeout
对象的 primitive 作为字符串或数字返回的Timeout
对象。¥
timeout
<Timeout> | <string> | <number> ATimeout
object as returned bysetInterval()
or the primitive of theTimeout
object as a string or a number.
取消由 setInterval()
创建的 Timeout
对象。
¥Cancels a Timeout
object created by setInterval()
.
clearTimeout(timeout)
#
-
timeout
<Timeout> | <string> | <number> 由setTimeout()
或Timeout
对象的 primitive 作为字符串或数字返回的Timeout
对象。¥
timeout
<Timeout> | <string> | <number> ATimeout
object as returned bysetTimeout()
or the primitive of theTimeout
object as a string or a number.
取消由 setTimeout()
创建的 Timeout
对象。
¥Cancels a Timeout
object created by setTimeout()
.
定时器 Promise API#
¥Timers Promises API
timers/promises
API 提供了一组可返回 Promise
对象的可供选择的定时器函数。API 可通过 require('node:timers/promises')
访问。
¥The timers/promises
API provides an alternative set of timer functions
that return Promise
objects. The API is accessible via
require('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> 在履行 promise 之前等待的毫秒数。默认值:1
。¥
delay
<number> The number of milliseconds to wait before fulfilling the promise. Default:1
. -
value
<any> 履行 promise 使用的值。¥
value
<any> A value with which the promise is fulfilled. -
options
<Object>-
ref
<boolean> 设置为false
以指示调度的Timeout
不应要求 Node.js 事件循环保持活动状态。默认值:true
。¥
ref
<boolean> Set tofalse
to indicate that the scheduledTimeout
should not require the Node.js event loop to remain active. Default:true
. -
signal
<AbortSignal> 可选的AbortSignal
,可用于取消调度的Timeout
。¥
signal
<AbortSignal> An optionalAbortSignal
that can be used to cancel the scheduledTimeout
.
-
import {
setTimeout,
} from 'node:timers/promises';
const res = await setTimeout(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> 履行 promise 使用的值。¥
value
<any> A value with which the promise is fulfilled. -
options
<Object>-
ref
<boolean> 设置为false
以指示调度的Immediate
不应要求 Node.js 事件循环保持活动状态。默认值:true
。¥
ref
<boolean> Set tofalse
to indicate that the scheduledImmediate
should not require the Node.js event loop to remain active. Default:true
. -
signal
<AbortSignal> 可选的AbortSignal
,可用于取消调度的Immediate
。¥
signal
<AbortSignal> An optionalAbortSignal
that can be used to cancel the scheduledImmediate
.
-
import {
setImmediate,
} from 'node:timers/promises';
const res = await setImmediate('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]]])
#
返回异步迭代器,以 delay
毫秒的间隔生成值。如果 ref
是 true
,则需要显式或隐式调用异步迭代器的 next()
,以保持事件循环存活。
¥Returns an async iterator that generates values in an interval of delay
ms.
If ref
is true
, you need to call next()
of async iterator explicitly
or implicitly to keep the event loop alive.
-
delay
<number> 迭代之间等待的毫秒数。默认值:1
。¥
delay
<number> The number of milliseconds to wait between iterations. Default:1
. -
value
<any> 迭代器返回的值。¥
value
<any> A value with which the iterator returns. -
options
<Object>-
ref
<boolean> 设置为false
以指示迭代之间的调度的Timeout
不应要求 Node.js 事件循环保持活动状态。默认值:true
。¥
ref
<boolean> Set tofalse
to indicate that the scheduledTimeout
between iterations should not require the Node.js event loop to remain active. Default:true
. -
signal
<AbortSignal> 可选的AbortSignal
,可用于在操作之间取消调度的Timeout
。¥
signal
<AbortSignal> An optionalAbortSignal
that can be used to cancel the scheduledTimeout
between operations.
-
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());
const {
setInterval,
} = require('node:timers/promises');
const interval = 100;
(async function() {
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());
})();
timersPromises.scheduler.wait(delay[, options])
#
¥Stability: 1 - Experimental
-
delay
<number> 解决 promise 前等待的毫秒数。¥
delay
<number> The number of milliseconds to wait before resolving the promise. -
options
<Object>-
ref
<boolean> 设置为false
以指示调度的Timeout
不应要求 Node.js 事件循环保持活动状态。默认值:true
。¥
ref
<boolean> Set tofalse
to indicate that the scheduledTimeout
should not require the Node.js event loop to remain active. Default:true
. -
signal
<AbortSignal> 可用于取消等待的可选AbortSignal
。¥
signal
<AbortSignal> An optionalAbortSignal
that can be used to cancel waiting.
-
-
返回:<Promise>
¥Returns: <Promise>
由 调度 API 规范草案定义的实验性 API 正在开发为标准 Web 平台 API。
¥An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API.
调用 timersPromises.scheduler.wait(delay, options)
相当于调用 timersPromises.setTimeout(delay, undefined, options)
。
¥Calling timersPromises.scheduler.wait(delay, options)
is equivalent
to calling timersPromises.setTimeout(delay, undefined, options)
.
import { scheduler } from 'node:timers/promises';
await scheduler.wait(1000); // Wait one second before continuing
timersPromises.scheduler.yield()
#
¥Stability: 1 - Experimental
由 调度 API 规范草案定义的实验性 API 正在开发为标准 Web 平台 API。
¥An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API.
调用 timersPromises.scheduler.yield()
等同于不带参数调用 timersPromises.setImmediate()
。
¥Calling timersPromises.scheduler.yield()
is equivalent to calling
timersPromises.setImmediate()
with no arguments.