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 tofalseto indicate that the scheduledTimeoutbetween iterations should not require the Node.js event loop to remain active. Default:true. -
signal<AbortSignal> 可选的AbortSignal,可用于在操作之间取消调度的Timeout。¥
signal<AbortSignal> An optionalAbortSignalthat can be used to cancel the scheduledTimeoutbetween 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());
})();