TExcelTAD
Home › Node.js › Timers & the Event Loop

Node.js Timers & the Event Loop

Node.js runs your JavaScript on a single thread, yet one server can handle thousands of connections at once. The trick is the event loop: slow operations (disk, network, timers) are handed to the operating system or a background thread pool, and when they finish, their callbacks are queued and run one after another on the main thread. Your code never waits — it registers what to do later and moves on.

Timers

Function Runs the callback… Cancel with
setTimeout(fn, ms) once, after at least ms milliseconds clearTimeout(t)
setInterval(fn, ms) repeatedly, every ms milliseconds clearInterval(t)
setImmediate(fn) once, right after the current I/O phase clearImmediate(i)
node · try it yourself
console.log('start');

setTimeout(() => console.log('timeout 20 ms'), 20);
setTimeout(() => console.log('timeout 0 ms'), 0);

let ticks = 0;
const interval = setInterval(() => {
  ticks++;
  console.log('tick', ticks);
  if (ticks === 3) clearInterval(interval);
}, 50);

const cancelled = setTimeout(() => console.log('never printed'), 10);
clearTimeout(cancelled);

console.log('end of script');
start
end of script
timeout 0 ms
timeout 20 ms
tick 1
tick 2
tick 3

end of script prints before any timer — even the 0 ms one — because callbacks only run once the current code has finished. The delay is a minimum, not a guarantee: a busy main thread delays every timer.

Note: In Node.js, setTimeout() returns a Timeout object (in browsers it's a number). Calling timer.unref() lets the program exit even if that timer is still pending — useful for background clean-up jobs.

Promise-based timers

node:timers/promises provides timers you can await — no callback nesting:

node · try it yourself
import { setTimeout as sleep, setInterval as every } from 'node:timers/promises';

console.log('waiting…');
const value = await sleep(30, 'result after 30 ms');
console.log(value);

let n = 0;
for await (const _ of every(20)) {
  n++;
  console.log('poll', n);
  if (n === 3) break;           // break stops the interval
}
waiting…
result after 30 ms
poll 1
poll 2
poll 3

The phases of the event loop

Each turn of the loop walks through a fixed set of phases. Each phase has its own queue of callbacks:

Phase Runs
timers expired setTimeout / setInterval callbacks
pending callbacks some deferred system callbacks
poll I/O callbacks (files, sockets); waits here when idle
check setImmediate callbacks
close callbacks 'close' events, e.g. socket.on('close')

Between every callback, Node empties two extra queues with the highest priority: first the process.nextTick queue, then the microtask queue (resolved promises, queueMicrotask).

node · try it yourself
const process = require('node:process'); // CommonJS script

console.log('1 synchronous');

setTimeout(() => console.log('6 timeout'), 0);

Promise.resolve().then(() => console.log('4 promise microtask'));
queueMicrotask(() => console.log('5 queueMicrotask'));
process.nextTick(() => console.log('3 nextTick'));

console.log('2 synchronous');
1 synchronous
2 synchronous
3 nextTick
4 promise microtask
5 queueMicrotask
6 timeout

Note: This order holds for CommonJS scripts. The top level of an ES module is itself evaluated inside a promise job, so there the microtasks queued at the top level (lines 4 and 5) run before the nextTick callback. Inside normal callbacks both module types behave the same.

Tip: The order of setTimeout(fn, 0) and setImmediate(fn) in the main script is not strictly guaranteed — it depends on how quickly the loop starts. Inside an I/O callback, however, setImmediate always runs first, because the check phase comes right after poll.

node · try it yourself
const { readFile } = require('node:fs');

readFile(__filename, () => {
  setTimeout(() => console.log('timeout'), 0);
  setImmediate(() => console.log('immediate'));
  process.nextTick(() => console.log('nextTick'));
});
nextTick
immediate
timeout

Don't block the loop

Because there is only one main thread, a long synchronous computation freezes everything: no timers fire and no requests are answered until it ends.

node · try it yourself
let fired = false;
setTimeout(() => {
  fired = true;
  console.log('timer finally ran');
}, 0);

// a busy loop of synchronous work
let sum = 0;
for (let i = 0; i < 5_000_000; i++) sum += i % 7;

console.log('heavy work done, timer fired yet?', fired);
heavy work done, timer fired yet? false
timer finally ran

Ways to keep the loop responsive:

  • use the asynchronous versions of APIs (fs/promises, not readFileSync, inside servers);
  • split long jobs into small pieces with setImmediate() between them;
  • move CPU-heavy work (image processing, big JSON, hashing) to worker threads or a child process.

Test yourself

Which callback runs first?

  1. setTimeout(fn, 0)
  2. setImmediate(fn)
  3. process.nextTick(fn)
  4. Promise.resolve().then(fn)

What does the delay in setTimeout(fn, 100) guarantee?

  1. fn runs exactly after 100 ms
  2. fn runs no earlier than 100 ms
  3. fn runs within 100 ms
  4. Nothing at all

Why is a long for loop dangerous inside an HTTP server?

  1. It uses too much disk
  2. It blocks the single main thread, so no other request is handled
  3. Node limits loops to 1 second
  4. It creates a memory leak