Mid-level (2-5 years)JavaScript

What is the event loop in JavaScript and how does it work?

Quick answer

The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it runs the call stack to empty, then runs all queued microtasks (promises), then takes the next task (timers, events) from the queue.

JavaScript runs one piece of code at a time on the call stack. Async operations such as timers, network requests and DOM events are handled by the browser (or Node.js), which places a callback in a queue when they finish. The event loop waits until the call stack is empty and then moves the next callback onto it.

There are two queues that matter. The macrotask queue holds timers, I/O and UI events. The microtask queue holds promise callbacks and queueMicrotask. After every task, the engine drains the entire microtask queue before taking the next macrotask, which is why a resolved promise runs before a setTimeout of 0.

A long synchronous task blocks everything, including rendering, because nothing else can run until the stack is empty. Splitting heavy work into chunks, using web workers, or yielding to the event loop keeps the page responsive.

console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Output: 1, 4, 3, 2
Synchronous code first, then microtasks, then timers.

Key points

  • One call stack, many queues
  • Microtasks (promises) run before the next macrotask (setTimeout)
  • Blocking the stack blocks rendering and input

Questions interviewers ask next

  • Why does setTimeout with 0 delay not run immediately?
  • How is the event loop different in Node.js?