Timers
| setTimeout | |
| setInterval | |
| Clear them | |
| unref in servers |
setTimeout
A timeout runs a callback once after a millisecond delay. Use it for retries, debounced saves, and friendly startup messages.
const timer = setTimeout(() => {
console.log("tick");
}, 500);
The delay is a minimum, not a promise of exact timing. Busy work can push the callback later, never earlier.
setInterval
An interval repeats the same callback on a steady cadence. It fits clocks, polls, and heartbeat logs.
let n: number = 0;
const clock = setInterval(() => {
n += 1;
console.log("beat " + n);
}, 1000);
Clear them
Every timer returns a handle, and every handle needs a matching clear call. Clearing stops future runs and lets short scripts exit.
const once = setTimeout(() => {
console.log("never");
}, 1000);
const tick = setInterval(() => {
console.log("beat");
}, 1000);
clearTimeout(once);
clearInterval(tick);
Cancel as soon as the work is done or no longer needed. Explicit cleanup beats hoping the process ends on its own.
unref in servers
A pending timer keeps Node alive by default, which can stall shutdown. The unref call marks housekeeping timers as non-blocking for exit.
const beat = setInterval(() => {
console.log("housekeeping");
}, 60000);
beat.unref();
Use unref for background cleanup only, never for work users wait for. Main responses stay referenced so they always complete.
Next: process
Article author: Arthur Isaev