Node.js v20.11.1 文档


定时器#

¥Timers

稳定性: 2 - 稳定的

¥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 处于活动状态,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 对象不需要 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]()#

稳定性: 1 - 实验性的

¥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()#

稳定性: 3 - 旧版:改用 clearTimeout()

¥Stability: 3 - Legacy: Use clearTimeout() instead.

取消超时。

¥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]()#

稳定性: 1 - 实验性的

¥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])#

在 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 the callback. Default: 1.

  • ...args <any> 调用 callback 时要传入的可选参数。

    ¥...args <any> Optional arguments to pass when the callback 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 the callback. Default: 1.

  • ...args <any> 调用 callback 时要传入的可选参数。

    ¥...args <any> Optional arguments to pass when the callback 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)#

取消由 setImmediate() 创建的 Immediate 对象。

¥Cancels an Immediate object created by setImmediate().

clearInterval(timeout)#

取消由 setInterval() 创建的 Timeout 对象。

¥Cancels a Timeout object created by setInterval().

clearTimeout(timeout)#

取消由 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 '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 to false to indicate that the scheduled Timeout should not require the Node.js event loop to remain active. Default: true.

    • signal <AbortSignal> 可选的 AbortSignal,可用于取消调度的 Timeout

      ¥signal <AbortSignal> An optional AbortSignal that can be used to cancel the scheduled Timeout.

import {
  setTimeout,
} from '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 to false to indicate that the scheduled Immediate should not require the Node.js event loop to remain active. Default: true.

    • signal <AbortSignal> 可选的 AbortSignal,可用于取消调度的 Immediate

      ¥signal <AbortSignal> An optional AbortSignal that can be used to cancel the scheduled Immediate.

import {
  setImmediate,
} from '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 毫秒的间隔生成值。如果 reftrue,则需要显式或隐式调用异步迭代器的 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 to false to indicate that the scheduled Timeout between iterations should not require the Node.js event loop to remain active. Default: true.

    • signal <AbortSignal> 可选的 AbortSignal,可用于在操作之间取消调度的 Timeout

      ¥signal <AbortSignal> An optional AbortSignal that can be used to cancel the scheduled Timeout between operations.

import {
  setInterval,
} from '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])#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

  • delay <number> 解决 promise 前等待的毫秒数。

    ¥delay <number> The number of milliseconds to wait before resolving the promise.

  • options <Object>

    • signal <AbortSignal> 可用于取消等待的可选 AbortSignal

      ¥signal <AbortSignal> An optional AbortSignal 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),只是不支持 ref 选项。

¥Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported.

import { scheduler } from 'node:timers/promises';

await scheduler.wait(1000); // Wait one second before continuing 

timersPromises.scheduler.yield()#

稳定性: 1 - 实验性的

¥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.