← 中文资源

简体中文版本

Timeout.refresh 重置看门狗倒计时

看门狗模式的关键是 refresh():每次活动把同一定时器的到期时间拨回去,不必 clearTimeout 再新建。活动停止后定时器真正到期,且只触发一次,适合空闲超时与会话保活。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

activity 1 refreshed the countdown
activity 2 refreshed the countdown
activity 3 refreshed the countdown
watchdog expired after 200ms of silence
watchdog fired exactly once: true

实现要点

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);