timersPromises.setInterval([delay[, value[, options]]])


返回异步迭代器,以 delay 毫秒的间隔生成值。 如果 reftrue,则需要显式或隐式调用异步迭代器的 next(),以保持事件循环存活。

  • delay <number> 迭代之间等待的毫秒数。 默认值: 1
  • value <any> 迭代器返回的值。
  • options <Object>
    • ref <boolean> 设置为 false 以指示迭代之间的调度的 Timeout 不应要求 Node.js 事件循环保持活动状态。 默认值: true
    • signal <AbortSignal> 可选的 AbortSignal,可用于在操作之间取消调度的 Timeout
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());
})();

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> The number of milliseconds to wait between iterations. Default: 1.
  • value <any> A value with which the iterator returns.
  • options <Object>
    • 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> 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());
})();