In Node.js, what does timeout.unref() do to a setInterval timer, and why would a socket server's idle-client sweeper call it?
answer
- what keeps a process alive
- timers are ref'd by default
- fires on time, but no longer counts
- server lives, sweeper follows
basics
~20 stimeout.unref() stops a timer from keeping the Node.js process alive. It still fires while other work, such as a listening server, keeps the loop running, so a housekeeping sweeper never becomes the reason the process cannot exit.
solid answer
~40 sEvery `Timeout` and `Immediate` is ref'd by default, and Node keeps the process running while any ref'd timer or handle is active. `timeout.unref()` takes the timer out of that count. It changes nothing about when the callback fires, only whether the timer alone can keep the process alive: while the server is listening, the sweeper runs on schedule; once the server has closed and the last client has gone, the process can exit even though the interval was never cleared. `unref()` returns the timer, so `setInterval(sweep, 10_000).unref()` is the usual one-liner; `ref()` undoes it, `hasRef()` reports the state, and the `node:timers/promises` functions accept `{ ref: false }`. Do not unref work that must finish, such as flushing a buffer, because the process may exit before it fires.
code
javascript · 18 linesconst net = require('node:net');
const lastSeen = new Map();
const server = net.createServer((socket) => {
lastSeen.set(socket, Date.now());
socket.on('data', () => lastSeen.set(socket, Date.now()));
socket.on('close', () => lastSeen.delete(socket));
});
setInterval(() => {
const cutoff = Date.now() - 60_000;
for (const [socket, seen] of lastSeen) {
if (seen < cutoff) socket.destroy();
}
}, 10_000).unref(); // the server, not the sweeper, decides whether the process lives
server.listen(3000);go deeper
Remember that Node exits when nothing keeps the loop alive, that timers keep it alive by default, and that unref() lets a timer run without holding the process open.
Explain ref, unref and hasRef, the fact that timing is unchanged, the ref: false option on the promise timers, and how refresh() reschedules a timer in place.
Show the judgment: unref housekeeping, never unref must-run work, and prefer clearing a timer in the shutdown path over unref'ing it to make a hang go away.
Set the convention for long-lived services: every background timer has an owner and a shutdown path, and unref is reserved for timers that are safe to drop.
## When does a Node.js process exit on its own? Node keeps running while its event loop has something to wait for, and exits when it has nothing. libuv defines this precisely: a loop is **alive** while it has **active and ref'd handles**, active requests or closing handles. In everyday terms, any of these keeps a process up: - a listening server or an open socket, - a pending file system or DNS request, - an active `Timeout` from `setTimeout` or `setInterval`, - a pending `Immediate` from `setImmediate`. "Ref'd" is the important word. Every timer and immediate is **ref'd by default**, meaning it counts towards keeping the loop alive. `unref()` removes it from that count. ## The ref and unref methods on timers | Method | Effect | Returns | |---|---|---| | `timeout.unref()` | the timer no longer requires the loop to stay alive | the same `Timeout` | | `timeout.ref()` | the timer keeps the loop alive again | the same `Timeout` | | `timeout.hasRef()` | `true` if the timer currently keeps the loop alive | a boolean | | `immediate.unref()` / `ref()` / `hasRef()` | the same, for an `Immediate` | the `Immediate` or a boolean | | `options.ref: false` in `node:timers/promises` | the promise timer starts unref'd | a promise or async iterator | A few details matter in interviews: - **`unref()` changes nothing about timing.** An unref'd interval fires on schedule as long as something else keeps the loop running. - **Calling `unref()` or `ref()` twice has no extra effect.** They are switches, not counters. - **Both return the timer**, so `setInterval(fn, ms).unref()` is a common one-liner that still leaves you a handle to clear. - **The promise timers take the same switch.** `await setTimeout(1_000, undefined, { ref: false })` from `node:timers/promises` waits without holding the process open, which suits a best-effort delay in a background task. - **An unref'd timer can be skipped entirely.** If nothing else keeps the loop alive, the process may exit before the callback runs, which the documentation states for both `Timeout` and `Immediate`. ## The idle-client sweeper A TCP server that tracks when each client last sent data, and periodically disconnects the silent ones, needs a repeating timer. That timer is housekeeping: it should run while the server runs and never be the reason the process stays up. ```js const sweeper = setInterval(evictIdleClients, 10_000); sweeper.unref(); ``` What then happens across the server's life: 1. While the server is listening, the server's handle keeps the loop alive and the sweeper fires every 10 seconds. 2. `server.close()` stops new connections; existing sockets still keep the loop alive and the sweeper keeps evicting idle ones. 3. When the last socket closes, nothing ref'd is left. The process exits, even though the interval was never cleared. Without `unref()`, step 3 never comes: the interval alone keeps the process running, and a deploy waits for a shutdown that never finishes. ## Where `unref()` is the wrong tool - **Work that must happen.** A timer that flushes buffered metrics or writes a final checkpoint must not be unref'd; the process may exit first and the work is lost. - **When you own the shutdown path.** If your code already has a place where the server closes, calling `clearInterval` there is clearer than relying on unref, and it also releases the callback and everything it references. - **As a fix for a hang you do not understand.** Unref'ing timers until the process exits hides which component forgot to clean up. - **Servers have their own switch.** `net.Server` and sockets offer `unref()` too, with the same meaning; that is part of the networking material. ## Related: `timeout.refresh()` A per-client idle timer is the other common design: one `setTimeout` per connection, pushed back each time data arrives. `timeout.refresh()` does that without allocating a new object: it sets the timer's start time to now and reschedules it for its original duration, and it reactivates a timer that has already fired. For sockets specifically, the socket's own idle-timeout setting covers the same need and is described with TCP sockets.
- What happens to a script whose only pending work is setTimeout(fn, 5000).unref()?It exits without calling `fn`. Once the main module has run, nothing ref'd is left in the event loop, so Node shuts down; the documentation warns that an unref'd timer's callback may never be invoked when no other activity keeps the loop running.
- When would you call ref() on a timer that was unref'd earlier?When the timer temporarily becomes essential. For example, a flush interval can run unref'd while the buffer is empty and be ref'd while it holds unsent data, so the process cannot exit with data still queued. `hasRef()` tells you which state it is in.
An unref'd timer is like a cleaner booked for the office: they keep working on schedule while staff are in, but the last person out locks up without waiting for them.
- unref() cancels the timer, like clearInterval does
- An unref'd interval stops firing while a server is still listening
- unref() is a good way to schedule work that must run before exit
- Calling unref() twice and then ref() once leaves the timer unref'd
- Unref'ing a timer frees the memory its callback holds