Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

The Event Loop — JavaScript interview guide

8 / 23Async JavaScriptHigh priorityHard 40 min

The Event Loop

JavaScript has one call stack. Slow work (timers, network) is handed to the browser. When it finishes, callbacks wait in queues, and the event loop pushes them onto the stack when it is empty.

See it run

Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.

Call Stack, Web APIs, queues and the Event Loop

Execution phaseStep 1/11
script.js
1console.log("Start");
2
3setTimeout(() => {
4 console.log("Timeout");
5}, 0);
6
7Promise.resolve().then(() => {
8 console.log("Promise");
9});
10
11console.log("End");
Call Stack
last in, first out
Globalrunning
Memory / Scope

empty

Web APIs (browser)
runs outside JS

empty

Event Loop

Waits until the Call Stack is empty. Microtasks always go first.

Microtask Queue
promises · high priority

empty

Callback Queue
setTimeout, events

empty

Console

nothing printed yet

What happens:The script starts. The Global context is on the Call Stack. JavaScript has ONE call stack, so it does one thing at a time.

Tip: click the box and use ← → keys to step, space to play.

Explained simply

The pieces

Call Stack: where code runs, one frame at a time.

Web APIs: browser features like setTimeout, fetch, DOM events. They work outside the JS thread.

Microtask Queue: promise callbacks (.then, await continuation), queueMicrotask, MutationObserver.

Callback (Task) Queue: setTimeout, setInterval, UI events, message events.

Event Loop: when the stack is empty, run ALL microtasks, then ONE task, then repeat (the browser may render between tasks).

Why setTimeout(fn, 0) is not instant

0ms is the MINIMUM delay. The callback still waits for the stack to be empty and for every microtask to finish.

Blocking the main thread

A long loop on the stack blocks everything: clicks, rendering and timers. Split heavy work into chunks or move it to a Web Worker.

button.onclick = () => {
  const end = Date.now() + 3000;
  while (Date.now() < end) {} // page frozen for 3 seconds
};

Remember this

  • Order: synchronous code → all microtasks → one macrotask → render → repeat.
  • Promise callbacks always beat setTimeout callbacks.
  • A microtask that keeps adding microtasks can starve rendering.

Interview questions

Predict: console.log(1); setTimeout(() => console.log(2)); Promise.resolve().then(() => console.log(3)); console.log(4);

1, 4, 3, 2. Sync logs first, then the promise microtask, then the timer task.

Microtask vs macrotask?

Microtasks (promises, queueMicrotask) run right after the current script and are all drained before the next macrotask (setTimeout, events, I/O).

Practice

  1. Add an async function with await into the example and predict the order.
  2. Use queueMicrotask and compare with setTimeout.

Keep learning