Event Loop (Node.js)
The event loop is the mechanism that lets single-threaded Node.js handle many operations concurrently. It runs your code, offloads I/O, and then processes completed callbacks in phases, never blocking on slow operations.
Node.js
Node runs your JavaScript on one thread, yet handles thousands of connections. The event loop makes this possible: when you start an async operation (read a file, query a database), Node hands it off and continues running other code; when the operation finishes, its callback is queued and run on the next loop tick.
The loop cycles through ordered phases — timers (setTimeout), pending callbacks, poll (I/O), check (setImmediate), and close callbacks — running the callbacks queued for each. Between phases (and after each callback) it drains the microtask queue, where resolved Promises and process.nextTick callbacks live, so those run before the next macrotask.
The practical lesson: never block the loop with long synchronous work (a heavy for-loop, a sync file read in a server), because while it runs, no other callback can fire and all requests stall. Offload CPU-bound work to worker threads or break it up.
Syntax
setTimeout(cb, 0); setImmediate(cb); Promise.resolve().then(cb);Examples
JavaScript
console.log("1 sync");
setTimeout(() => console.log("3 timeout"), 0);
Promise.resolve().then(() => console.log("2 microtask"));
console.log("1b sync");Output:
1 sync
1b sync
2 microtask
3 timeout