实现要点
200ms 的定时器启动看门狗。三次活动间隔 80ms,每次 watchdog.refresh() 把同一个定时器的到期时间拨后 200ms——打印三行 activity,没有 clearTimeout,也没有新建定时器对象。
刷新停止后,250ms 的等待超过最后一次 200ms 倒计时,回调终于执行一次,fired 打印 1。示例断言 fired === 1——refresh 过的定时器只触发一次,而不是每次 refresh 各触发一次。
细节提醒
- refresh() 原地重置现有定时器;句柄保持有效。
- 空闲检测由该模式自然得出:静默超过延时就到期。
核心语句
watchdog.refresh();
代码示例
import { setTimeout as delay } from 'node:timers/promises';
// Watchdog pattern: every activity resets the countdown instead of clearTimeout/setTimeout cycles
let fired = 0;
const watchdog = setTimeout(() => {
fired += 1;
console.log('watchdog expired after 200ms of silence');
}, 200);
// Three activities 80ms apart: each refresh pushes expiry 200ms further out
for (let i = 1; i <= 3; i++) {
await delay(80);
watchdog.refresh();
console.log('activity', i, 'refreshed the countdown');
}
// Once refreshing stops, the watchdog really expires - and fires exactly once
await delay(250);
console.log('watchdog fired exactly once:', fired === 1);