Glossary / Event loop

Event loop

An event loop coordinates when queued JavaScript work runs and, in browsers, when input, timers, microtasks, rendering, and other host work are processed. JavaScript code is synchronous within a job; asynchronous APIs arrange for callbacks or Promise reactions to run later. The browser HTML event loop and Node.js event loop are related concepts but have different phases and host-specific scheduling rules.

Browser model

A simplified browser cycle selects a task (often called a macrotask), runs it to completion, drains microtasks, and may then update rendering before continuing. Tasks include events, timers, and message handling; Promise reactions and queueMicrotask callbacks are microtasks. Rendering opportunities are browser-controlled and are not guaranteed after every task. requestAnimationFrame callbacks are coordinated with rendering; idle callbacks are opportunistic.

console.log("sync");
setTimeout(() => console.log("task"), 0);
Promise.resolve().then(() => console.log("microtask"));
// sync, microtask, task (in the usual browser ordering)

This ordering does not mean all asynchronous mechanisms share one simple FIFO queue. Task sources and scheduling policies matter. A microtask that enqueues more microtasks can starve rendering and tasks because the queue is drained until empty.

Node.js model

Node’s event loop includes phases such as timers, pending callbacks, poll, check, and close callbacks, plus Node-specific process.nextTick and Promise microtask behavior. Exact ordering differs from browsers and can vary by context and version. Node also uses libuv and a worker pool for some operations; JavaScript callbacks still execute on the event-loop thread unless moved to worker threads.

Engineering guidance

Avoid long synchronous work. Use Promises for async composition, timers only for delays (not precise clocks), animation-frame callbacks for visual updates, and workers for CPU-intensive work. When ordering matters, test the actual host/runtime and use the relevant spec/documentation rather than relying on folklore.

Interview questions

  1. What is the event loop for? Scheduling jobs and coordinating async host work with JavaScript execution.
  2. Where do Promise reactions run in browsers? On the microtask queue after the current job’s stack unwinds.
  3. Are browser and Node event loops identical? No; hosts define different scheduling phases and APIs.
  4. Can microtasks starve rendering? Yes, if microtasks keep enqueueing additional microtasks.
  5. Does async/await create a thread? No; it suspends continuation and schedules future work.

References