JavaScript event loop, explained

A short guide tied to Event Loop Analyser, a free open-source visualizer.

In one line: after sync code finishes, JavaScript drains all microtasks before the next macrotask (like a setTimeout callback).

The four places work sits

  1. Call stack — what’s running right now
  2. Web APIs — timers waiting (e.g. setTimeout)
  3. Microtask queue — Promise.then / catch, queueMicrotask
  4. Callback queue — macrotasks ready to run

Promise vs setTimeout(0)

console.log("s1");
setTimeout(() => console.log("macro"), 0);
Promise.resolve().then(() => console.log("micro"));
console.log("s2");

Console order: s1, s2, micro, macro.

Step through this live in Event Loop Analyser (preset: “Promise vs timeout”).

What Event Loop Analyser is

An interactive Loupe-style tool: paste JavaScript, press Run or Step, and watch panels update. It teaches interview-style ordering for a supported subset of JS (timers + Promises + queueMicrotask). MIT licensed.

FAQ

Does the Promise executor run async? No — it runs synchronously. Handlers passed to .then run as microtasks.

Is this a full browser engine? No — it’s a teaching simulator. Unsupported syntax errors instead of guessing.