Timeout Refresh Resets The Watchdog Countdown
refresh() rearms a running timer in place, the primitive behind idle watchdogs: every heartbeat pushes the deadline out without recreating the timeout.
Code
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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
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: trueWhat the demo rearms
A 200ms timeout starts the watchdog. Three activities run 80ms apart, and each watchdog.refresh() pushes the same timer deadline 200ms further out — three printed activity lines, no clearTimeout, no new timeout object.
Once refreshing stops, the 250ms wait outlasts the last 200ms countdown, so the callback finally runs once and fired prints exactly one. The demo asserts fired === 1, showing the refreshed timer fires a single time, not per refresh.
Caveats and details
- refresh() mutates the existing timer; the handle stays valid.
- Idle detection falls out of the pattern: silence longer than the delay expires it.
Interactive Tools for This Topic
FAQ
- Does refresh() create a new timer?
- No; it rearms the same Timeout in place. The demo reuses one watchdog handle for all three activities, and the final assert confirms exactly one firing.
Report a problem with this exampleOpens a pre-filled issue on GitHub.