Event Loop
The event loop is the host's scheduler: it waits for the call stack to empty, drains all pending microtasks, then runs one queued task. It is what lets single-threaded JavaScript handle timers, clicks and network replies without blocking.
Detailed Explanation
Start with the part most articles get wrong. The event loop is not part of the JavaScript language. The ECMAScript specification describes an agent with one execution thread and a queue of jobs, and stops there. The loop itself lives in the host: the browser (defined by the HTML specification) or Node.js (built on libuv). That is why setTimeout, fetch and setImmediate are not in the language spec. They are host capabilities.
The consequence matters. Your JavaScript runs on one thread. Only one function executes at a time. Concurrency comes from the host doing work elsewhere (a network thread, a timer, a thread pool) and handing results back to your single thread when it is free.
One turn of the loop, in order:
- Run the current task to completion. Nothing interrupts it.
- When the call stack is empty, drain the entire microtask queue, including microtasks that other microtasks queue while draining.
- In a browser, possibly run the rendering steps:
requestAnimationFramecallbacks, style, layout, paint. - Take one task (macrotask) from the task queue and go back to step 1.
The phrase "drain the entire microtask queue" is the detail that separates people who understand this from people who have memorised a diagram. Microtasks are not one-per-turn. The loop keeps pulling until the queue is empty. A microtask that queues another microtask forever starves the task queue completely: timers never fire, clicks never dispatch, the page freezes, and there is no way out.
Microtasks are .then/.catch/.finally reactions, await continuations, queueMicrotask callbacks, and MutationObserver callbacks. Macrotasks are setTimeout, setInterval, I/O completions, UI events, and setImmediate in Node. requestAnimationFrame is neither: it belongs to the browser's rendering steps and runs before paint.
Node runs the same idea with named phases per iteration: timers (setTimeout, setInterval), pending callbacks, poll (I/O), check (setImmediate), and close callbacks. Node adds process.nextTick, which has its own queue that drains before the promise microtask queue. In modern Node, both queues drain between each individual macrotask callback; in Node 10 and earlier they drained only between phases, which is why old blog posts disagree with what you observe today. process.nextTick and setImmediate are Node-only and do not exist in browsers.
When you reach for this knowledge: reasoning about log order, fixing a UI that stutters, or explaining why a 200 ms synchronous loop makes a button unresponsive. The event loop's cost is the flip side of its simplicity. There is no preemption. Any long synchronous function delays every timer, every event and every frame behind it. Yielding is your job, not the scheduler's.
Code Examples
Node. Run with: node order.js
// Node. Run with: node order.js
console.log("1: sync start");
setTimeout(() => console.log("5: setTimeout 0"), 0); // timers phase
setImmediate(() => console.log("6: setImmediate")); // check phase, Node only
process.nextTick(() => console.log("3: nextTick")); // Node-only queue, drains first
Promise.resolve().then(() => console.log("4: promise then")); // microtask
console.log("2: sync end");
// => 1: sync start
// => 2: sync end
// => 3: nextTick (nextTick queue drains before promise microtasks)
// => 4: promise then (microtask queue drained fully before any macrotask)
// The last two are NOT deterministic at the top level of a script: whether the
// timer is already "due" when the loop starts depends on process start-up time.
// Inside an I/O callback the order is fixed. See the next example.Node. Inside an I/O callback the loop is already past the timers phase,
// Node. Inside an I/O callback the loop is already past the timers phase,
// so the check phase (setImmediate) always wins over the next timers phase.
const fs = require("node:fs");
fs.readFile(__filename, () => {
setTimeout(() => console.log("second: setTimeout"), 0);
setImmediate(() => console.log("first: setImmediate"));
});
// => first: setImmediate
// => second: setTimeoutBrowser. One long synchronous task blocks everything behind it.
// Browser. One long synchronous task blocks everything behind it.
const button = document.querySelector("#run");
button.addEventListener("click", () => {
const end = Date.now() + 3000;
while (Date.now() < end) {} // 3 seconds of blocking work
// During this loop: no paint, no other click handler, no timer callback.
});
// The fix is to yield. Each await lets the loop render a frame before resuming.
async function chunked(items, work) {
for (let i = 0; i < items.length; i++) {
work(items[i]);
// Every 500 items, hand control back to the event loop for one task turn.
if (i % 500 === 0) await new Promise((resolve) => setTimeout(resolve, 0));
}
}Common Gotchas
Microtasks are drained fully, not one per turn
a `.then` that queues another `.then` in an unbounded chain never lets a timer or a click through. The tab locks up with no error and no stack trace.
The event loop is not in the language
it is provided by the browser or Node. Two hosts can legitimately order the same code differently, which is why `setTimeout` versus `setImmediate` at top level in Node has no guaranteed winner.
`requestAnimationFrame` is not a macrotask
it runs in the rendering steps, right before paint, at most once per frame. Use it for animation, `setTimeout` for delay, and neither for "run after the current work".
Blocking the thread has no timeout
there is no watchdog that interrupts your loop. The browser may eventually offer to kill the page, but nothing in JavaScript rescues you. Move CPU-heavy work to a worker.