Reading history

The JavaScript Event Loop: Call Stack, Tasks and Microtasks

5 min read 0 views

Understand the JavaScript event loop: the call stack, task and microtask queues, setTimeout 0, promises and await ordering, and avoiding blocking code.

JavaScript runs your code on a single thread: it can only do one thing at a time. Yet pages load data, run timers and respond to clicks all at once. The trick is the event loop, which lets slow work happen in the background and then queues the callbacks to run one by one when the main code is free. Knowing how it orders tasks explains surprising output and helps you keep pages smooth.

In this lesson you will learn

  • The call stack and what “single-threaded” means
  • Web APIs, the task queue and the microtask queue
  • Why setTimeout(fn, 0) does not run immediately
  • Where promises and await fit in the order
  • How long-running code freezes a page, and how to avoid it

This lesson builds on Promises and async/await.

Tasks and Microtasks

console.log("1. script start");

setTimeout(() => console.log("5. setTimeout callback (task queue)"), 0);

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

queueMicrotask(() => console.log("4. queueMicrotask (microtask)"));

console.log("2. script end");

Output

1. script start
2. script end
3. promise callback (microtask)
4. queueMicrotask (microtask)
5. setTimeout callback (task queue)
  • All the ordinary lines run first, top to bottom, on the call stack. That is why “script end” prints before any callback, even one with a 0 ms delay.
  • setTimeout hands the timer to the browser (or Node.js). When it expires, its callback is placed in the task queue (also called the macrotask queue).
  • Promise callbacks (.then) and queueMicrotask go into the microtask queue.
  • When the call stack is empty, the event loop runs all waiting microtasks first, then takes one task from the task queue, then checks microtasks again, and repeats.

async/await in the Loop

async function loadData() {
  console.log("2: inside loadData, before await");
  await null;                                   // pauses here, resumes as a microtask
  console.log("4: after await");
}

console.log("1: start");
setTimeout(() => console.log("7: timeout 0"), 0);
loadData();
Promise.resolve()
  .then(() => console.log("5: then #1"))
  .then(() => console.log("6: then #2 (still before the timer)"));
console.log("3: end of script, call stack now empty");

Output

1: start
2: inside loadData, before await
3: end of script, call stack now empty
4: after await
5: then #1
6: then #2 (still before the timer)
7: timeout 0
  • Calling loadData() runs its body synchronously until the first await, so line 2 prints straight after line 1.
  • await pauses the function and schedules the rest of it as a microtask. Control returns to the caller, which prints line 3.
  • With the stack empty, the microtasks run in the order they were queued: the rest of loadData, then the first .then. That .then queues the second one, which also runs before the timer, because the microtask queue is emptied completely before any task.
  • The setTimeout callback, although registered early, comes last.

Which Queue?

SourceQueuePriority
Your script, function callsCall stackRuns now
promise.then, await, queueMicrotaskMicrotask queueAll run as soon as the stack is empty
setTimeout, setIntervalTask queueOne per loop turn
Clicks, key presses, network eventsTask queueOne per loop turn
requestAnimationFrameBefore the next repaintAbout 60 times per second

Do Not Block the Loop

// BAD: a 3-second busy loop freezes clicks, scrolling and animations
button.addEventListener("click", () => {
  const end = Date.now() + 3000;
  while (Date.now() < end) {}          // nothing else can run meanwhile
});

// BETTER: split big jobs into chunks and yield between them
async function processAll(items) {
  for (let i = 0; i < items.length; i++) {
    handle(items[i]);
    if (i % 500 === 0) await new Promise(r => setTimeout(r, 0));  // let the page breathe
  }
}

While a script runs, the browser cannot paint or respond. Keep each piece of work short, split long loops, and move heavy calculations into a Web Worker, which runs on a separate thread.

Common Mistakes

  1. Expecting setTimeout(fn, 0) to run instantly; it waits for the stack and all microtasks. The delay is a minimum, not a promise.
  2. Reading a value set in a callback on the next line, before the callback has run.
  3. Endless microtask chains, which starve timers and rendering just like a busy loop.
  4. Heavy synchronous work in event handlers, making the page feel frozen.

Practice Exercises

Exercise 1. Predict the output, then run it.

setTimeout(() => console.log("A"), 0);
Promise.resolve().then(() => console.log("B"));
console.log("C");
Show answer

C, B, A. Synchronous code first, then microtasks (the promise), then tasks (the timer).

Exercise 2. Two timers are set: setTimeout(a, 100) then setTimeout(b, 50). Which runs first?

Show answer

b, because its delay expires first and it reaches the task queue sooner. Order of registration does not matter for different delays.

Frequently Asked Questions

If JavaScript is single-threaded, how does fetch run in parallel?

The network request is handled by the browser outside the JavaScript thread. Only the callback that processes the response runs on the main thread, after the event loop picks it up.

Is the event loop the same in Node.js?

The core idea is the same: call stack, microtasks, then tasks. Node.js has extra phases (for example for file I/O and setImmediate), but promise and timer ordering in simple examples like these matches the browser.

Summary

  • One call stack runs code to completion.
  • Microtasks (promises, await) run before the next task (timers, events).
  • setTimeout(fn, 0) means “as soon as possible after current work”.
  • Keep work short so the page stays responsive.

Next: JavaScript Form Validation.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *