Node.js v20.20.6 文档


定时器#>

【Timers】

源代码: lib/timers.js

timer 模块提供了一个全局 API,用于安排函数在未来的某个时间被调用。由于定时器函数是全局的,因此使用该 API 时无需调用 require('node:timers')

【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 类似的接口,但使用了不同的内部实现,该实现是围绕 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.】

默认情况下,当一个 immediate 被调度时,只要该 immediate 处于活动状态,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()#>

如果为真,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 - 实验性

取消立即执行。这类似于调用 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()

取消超时。

【Cancels the timeout.】

timeout.hasRef()#>

如果为真,Timeout 对象将保持 Node.js 事件循环处于活动状态。

【If true, the Timeout object will keep the Node.js event loop active.】

timeout.ref()#>

当被调用时,会请求 Node.js 事件循环在 Timeout 活跃期间保持运行。多次调用 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 的数字

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 - 实验性

取消超时。

【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

【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.】

这种方法有一个适用于 Promise 的自定义变体,可以通过 timersPromises.setImmediate() 使用。

【This method has a custom variant for promises that is available using timersPromises.setImmediate().】

setInterval(callback[, delay[, ...args]])#>

  • callback <Function> 定时器到期时要调用的函数。
  • delay <number> 调用 callback 之前要等待的毫秒数。默认值: 1
  • ...args <any> 调用 callback 时要传递的可选参数。
  • 返回值:<Timeout>,用于 clearInterval()

安排 callback 每隔 delay 毫秒重复执行。

【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.】

这种方法有一个适用于 Promise 的自定义变体,可以通过 timersPromises.setInterval() 使用。

【This method has a custom variant for promises that is available using timersPromises.setInterval().】

setTimeout(callback[, delay[, ...args]])#>

  • callback <Function> 定时器到期时要调用的函数。
  • delay <number> 调用 callback 之前要等待的毫秒数。默认值: 1
  • ...args <any> 调用 callback 时要传递的可选参数。
  • 返回值:<Timeout>,用于 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.】

这种方法有一个适用于 Promise 的自定义变体,可以通过 timersPromises.setTimeout() 使用。

【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() 的承诺化变体,可以使用 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():】

import { setImmediate as setImmediatePromise } from 'node:timers/promises';

const ac = new AbortController();
const signal = ac.signal;

// We do not `await` the promise so `ac.abort()` is called concurrently.
setImmediatePromise('foobar', { signal })
  .then(console.log)
  .catch((err) => {
    if (err.name === 'AbortError')
      console.error('The immediate was aborted');
  });

ac.abort();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():】

import { setTimeout as setTimeoutPromise } from 'node:timers/promises';

const ac = new AbortController();
const signal = ac.signal;

// We do not `await` the promise so `ac.abort()` is called concurrently.
setTimeoutPromise(1000, 'foobar', { signal })
  .then(console.log)
  .catch((err) => {
    if (err.name === 'AbortError')
      console.error('The timeout was aborted');
  });

ac.abort();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 'node:timers/promises';const {
  setTimeout,
  setImmediate,
  setInterval,
} = require('node:timers/promises');

timersPromises.setTimeout([delay[, value[, options]]])#>

  • delay <number> 在完成 Promise 之前等待的毫秒数。默认值: 1
  • value <any> 用于完成 Promise 的值。
  • options <Object>
    • ref <boolean> 设置为 false 表示计划的 Timeout 不需要保持 Node.js 事件循环活动。 默认值: true
    • signal <AbortSignal> 可选的 AbortSignal,可以用来取消计划的 Timeout
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 的值。
  • options <Object>
    • ref <boolean> 设置为 false 表示计划的 Immediate 不需要保持 Node.js 事件循环处于活动状态。 默认值: true
    • signal <AbortSignal> 一个可选的 AbortSignal,可用于取消计划的 Immediate
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 毫秒的间隔生成值。如果 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
  • value <any> 迭代器返回的值。
  • options <Object>
    • ref <boolean> 设置为 false 表示在迭代之间调度的 Timeout 不需要 Node.js 事件循环保持活跃。 默认值: true
    • signal <AbortSignal> 一个可选的 AbortSignal,可用于取消操作之间调度的 Timeout
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])#>

稳定性: 1 - 实验性

  • delay <number> 在解析 Promise 之前等待的毫秒数。
  • options <Object>
    • ref <boolean> 设置为 false 表示计划的 Timeout 不需要 Node.js 事件循环保持活动状态。 默认值: true
    • signal <AbortSignal> 可选的 AbortSignal,可用于取消等待。
  • 返回: <Promise>

调度 API 草案规范定义的实验性 API,正在作为标准网页平台 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()#>

稳定性: 1 - 实验性

调度 API 草案规范定义的实验性 API,正在作为标准网页平台 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.】

Node.js 中文网 - 粤ICP备13048890号