SkillPilotAI

Event loop

JavaScript runs on a single thread, yet timers, fetch and clicks all work without blocking. The event loop is the mechanism behind that, and its microtask vs macrotask order is the answer to the classic output-order puzzles asked in interviews.

15.1 The problem: a late 0 ms timer

  • setTimeout(..., 0) is scheduled, then a while loop keeps the CPU busy for 3 seconds.
  • You might expect Timer done immediately, but it prints last, after 3 seconds.
JavaScript
console.log("Order placed"); setTimeout(() => {  console.log("Timer done");}, 0); const start = Date.now();while (Date.now() - start < 3000) {  // 3 seconds ka heavy kaam} console.log("Heavy work done");
Output
Order placedHeavy work doneTimer done

15.2 Why was the timer late?

  • JavaScript has one call stack; while code runs on it, no other callback can run.
  • The timer callback was ready after 0 ms but waited in the queue while the loop blocked the stack.
  • The setTimeout delay is a minimum time, not a guarantee; the callback runs only when the stack is empty.

15.3 The 4 parts of the event loop

PartWhat it doesExamples
Call stackRuns synchronous code line by lineconsole.log, loops, function calls
Web APIsBrowser (or Node) does async work in the background, outside JSTimers, fetch, click events
QueuesReady callbacks wait in lineMicrotask queue, macrotask (task) queue
Event loopWhen the stack is empty, moves the next callback to itRepeats forever
One turn of the event loop
  1. 1.Run all synchronous code on the call stack

  2. 2.Stack empty -> run ALL microtasks (Promise then/catch, code after await)

  3. 3.Microtask queue empty -> browser may update the screen

  4. 4.Take ONE macrotask (setTimeout, click) and run it

  5. 5.Run all microtasks again, then repeat

Microtasks always go before the next macrotask

15.4 Classic puzzle: 1, 2, 3, 4

JavaScript
console.log("1"); setTimeout(() => {  console.log("2");}, 0); Promise.resolve().then(() => {  console.log("3");}); console.log("4");
Output
1432
  1. Sync code runs first: 1, then 4.
  2. The timer callback goes to the macrotask queue; the then callback goes to the microtask queue.
  3. Stack empty: all microtasks run, so 3.
  4. Then one macrotask runs, so 2 comes last.

15.5 Checkpoint: async/await in the order

JavaScript
console.log("A"); setTimeout(() => console.log("B"), 0); async function run() {  console.log("C");  await null;  console.log("D");} run();Promise.resolve()  .then(() => console.log("E"));console.log("F");
Output
ACFDEB
Why A C F D E B
  1. 1.Sync: A; B's timer -> macrotask queue

  2. 2.run() starts: C prints synchronously

  3. 3.await null -> rest of run (D) becomes a microtask

  4. 4.then(E) -> microtask queued after D; F prints (sync)

  5. 5.Microtasks in order: D, E

  6. 6.Macrotask: B

15.6 Comparison: microtask vs macrotask

PointMicrotaskMacrotask (task)
SourcesPromise then/catch/finally, code after await, queueMicrotasksetTimeout, setInterval, click/DOM events, I/O
How many per turnAll of them, until the queue is emptyOne
Order vs the otherBefore the next macrotaskAfter all microtasks
RiskEndless chain blocks screen updatesDelay is only a minimum

15.7 Common mistake: a heavy loop freezes the page

  • One long loop over thousands of orders keeps the stack busy: clicks and scrolling do nothing.
  • Fix: process in chunks and yield to the event loop every 1000 items with a tiny await.
  • For really heavy calculations, move the work to a Web Worker.
JavaScript
// Wrong: page frozen until the loop endsfunction processAll(orders) {  for (const order of orders) {    calculateBill(order);  }  showDone();} // Right: a break every 1000, clicks still workasync function processAll(orders) {  for (let i = 0; i < orders.length; i++) {    calculateBill(orders[i]);    if (i % 1000 === 0) {      await new Promise((r) => setTimeout(r));    }  }  showDone();}

15.8 Misconceptions and rules

  • await does not stop the program; only that async function pauses (F printed before D).
  • setTimeout 0 does not mean immediately: it runs after the current code and after all microtasks.
  • Do not run long synchronous work on the main thread: chunks or a Web Worker.
  • Do not create endless microtask chains: the screen cannot update until the microtask queue is empty.
  • Node uses the same event loop idea, with slightly different phases.

15.9 Interview tips

  • JavaScript is single threaded; async work (timers, fetch) is handled by Web APIs.
  • Finished work puts callbacks in queues; the event loop moves them to the stack when it is empty.
  • All microtasks run before every macrotask, so Promise.then beats setTimeout 0.
  • Code after await is a microtask.
  • Walk through 1, 4, 3, 2 out loud when given an ordering puzzle.