The Heart of JavaScript

The Event Loop is the mechanism that allows JavaScript to perform non-blocking operations despite being single-threaded. It is an endless loop that picks up tasks, executes them, and waits for more.

One Iteration of the Event Loop:

  1. Pick one Macrotask from the queue and execute it (e.g., run a script, fire a click event).
  2. Execute ALL Microtasks in the queue until it is completely empty.
  3. Render: Update the screen if any visual changes were made.
  4. If no tasks are waiting, go to sleep until a new macrotask arrives.

Why Does This Matter?

This understanding lets you write non-blocking code. If you have a heavy computation, you can split it into chunks using setTimeout, giving the browser a chance to render frames in between.

// Bad: Blocks the browser for the entire duration
function heavyComputation() {
  for (let i = 0; i < 1_000_000_000; i++) { /* ... */ }
}
heavyComputation(); // Page freezes!

// Better: Yield back to the Event Loop between chunks
function processChunk(i) {
  if (i >= 1_000_000_000) return;
  // Do a small chunk of work
  for (let j = i; j < i + 10_000; j++) { /* ... */ }
  setTimeout(() => processChunk(i + 10_000), 0); // Schedule next chunk
}
processChunk(0);
Tip

A single Event Loop iteration should ideally take no more than 16.6ms (to maintain 60 frames per second). If your macrotask takes longer, users will see visible stuttering and lag.