unref Frees The Event Loop From Timers
unref detaches a timer from the event loop so background heartbeats cannot keep the process alive after the real work has finished.
Code
// 保活心跳:不 unref 的话,进程会为这个 60 秒的 timer 多活一分钟
const keepAlive = setTimeout(() => console.log("heartbeat fired"), 60_000);
keepAlive.unref(); // 事件循环不再把它算作待办工作
// 真正的业务:完成即退出,不等保活 timer
console.log("report generated");
await new Promise((resolve) => setTimeout(resolve, 20));
console.log("work done: exiting without waiting for the heartbeat");
What the code does
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The file’s state is a handful of top-level bindings: keepAlive.
Watch out for
- The dependency list is empty; the language runtime covers it all.
Applying it
The run prints only 2 lines — report generated, then work done: exiting without waiting for the heartbeat. heartbeat fired never appears: after .unref(), the 60-second timer is not event-loop work, so Node exits once the awaited 20ms step finishes instead of waiting out the heartbeat. That absence is exactly what this snippet demonstrates.
Statements that matter
await new Promise((resolve) => setTimeout(resolve, 20));
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `keepAlive`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.