CPCODELAB
JavaScript

The Event Loop

10 min read

How the Event Loop Works

JavaScript is single-threaded, yet it can handle network requests, timers, and user events without freezing the page. The event loop is the mechanism that makes this possible.

The runtime has: a call stack (where synchronous code runs), a heap (memory for objects), a task queue (macrotasks: setTimeout, setInterval, I/O callbacks), and a microtask queue (Promise callbacks, queueMicrotask).

javascript
console.log("1"); // synchronous

setTimeout(() => console.log("2"), 0); // macrotask

Promise.resolve().then(() => console.log("3")); // microtask

console.log("4"); // synchronous

// Output order: 1, 4, 3, 2

The event loop cycle: run all synchronous code → drain the entire microtask queue → pick ONE macrotask → drain the microtask queue again → repeat.

Why This Matters

  • Microtasks (Promises) always run before the next timer callback — even a setTimeout(..., 0)
  • A long synchronous loop blocks the entire UI because the event loop cannot process events while the call stack is occupied
  • Breaking heavy computation into smaller chunks (with setTimeout 0 or queueMicrotask) keeps the UI responsive
  • Understanding this helps you predict the exact order of logs — a common interview topic at places like CPCODELAB

Web Workers let you run JavaScript on a background thread, offloading CPU-heavy work without blocking the main thread. They communicate via postMessage and cannot access the DOM directly.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises