JavaScript Event Loop Explained: Call Stack, Task Queue and Microtasks

JavaScript runs your code on a single thread, yet a Node.js server handles thousands of requests and a Playwright test waits for pages, clicks and network calls without freezing. The mechanism behind this is the event loop. Understanding it explains the order in which callbacks and promises run, why setTimeout(fn, 0) is not instant, why a long loop freezes everything, and why a missing await makes tests flaky. This lesson builds that understanding step by step, with outputs you can predict.

Advertisement

📖 What You’ll Learn: what single-threaded means, the call stack, how the runtime (browser or Node.js) does slow work in the background, the task (macrotask) queue, the microtask queue for promises, the order the event loop follows, setTimeout(fn, 0), process.nextTick and queueMicrotask, blocking the event loop, starving it with microtasks, and what this means for writing reliable tests.


🧵 Single-Threaded, but Not Blocking

Definition: JavaScript is single-threaded: one piece of your code runs at a time, on one call stack. Slow operations (timers, network requests, file reads, browser events) are handed to the runtime (the browser or Node.js), which does them in the background. When one finishes, its callback is put in a queue. The event loop takes callbacks from the queues and runs them, but only when the call stack is empty.

📄 basics.js

console.log("1. start");

setTimeout(() => console.log("4. timer callback"), 0);   // handed to the runtime

console.log("2. still running synchronous code");
for (let i = 0; i < 3; i++) console.log("3. loop", i);
// the stack empties here, then the event loop runs the queued timer callback

⌨️ Terminal

node basics.js

🖥️ Output

1. start
2. still running synchronous code
3. loop 0
3. loop 1
3. loop 2
4. timer callback
  • All synchronous code runs first, from top to bottom, without interruption.
  • setTimeout only schedules its callback; even with 0 ms it runs later.
  • The timer callback runs once the call stack is empty.

📚 The Call Stack

Definition: the call stack records which functions are running. Calling a function pushes it on the stack; returning pops it off. The program only does one thing at a time: whatever is on top of the stack.

📄 call-stack.js

function third() {
  console.trace("inside third");   // prints the current call stack
}
function second() { third(); }
function first() { second(); }
first();

⌨️ Terminal

node call-stack.js

🖥️ Output

Trace: inside third
    at third (/home/you/js-course/call-stack.js:2:11)
    at second (/home/you/js-course/call-stack.js:4:21)
    at first (/home/you/js-course/call-stack.js:5:20)
    at Object.<anonymous> (/home/you/js-course/call-stack.js:6:1)

Error stack traces are a snapshot of this same stack, which is why they list the most recent call first.


📬 Task Queue and Microtask Queue

There are two main queues of waiting callbacks, and they have different priorities:

QueueFilled byWhen it runs
Microtask queuePromise reactions (.then, .catch, code after await), queueMicrotaskImmediately after the current task, completely emptied before anything else
Task (macrotask) queuesetTimeout, setInterval, I/O callbacks, UI events, setImmediate (Node.js)One task per loop turn, after all microtasks are done

The event loop repeats these steps:

  1. Run the current task (at the start: your whole script) until the call stack is empty.
  2. Run all microtasks, including any new microtasks they add.
  3. In the browser, update rendering if needed.
  4. Take the next task from a task queue and go back to step 1.

📄 queues.js

console.log("A: script start");

setTimeout(() => console.log("E: timeout (task)"), 0);

Promise.resolve().then(() => console.log("C: promise then (microtask)"));
queueMicrotask(() => console.log("D: queueMicrotask (microtask)"));

console.log("B: script end");

⌨️ Terminal

node queues.js

🖥️ Output

A: script start
B: script end
C: promise then (microtask)
D: queueMicrotask (microtask)
E: timeout (task)

The promise and queueMicrotask callbacks run before the timer, even though the timer was scheduled first, because microtasks always run before the next task.


Advertisement

🧩 Predict the Order: A Classic Puzzle

Interviewers love this kind of question. Read it, predict the output using the rules above, then compare:

📄 puzzle.js

console.log(1);

setTimeout(() => {
  console.log(2);
  Promise.resolve().then(() => console.log(3));
}, 0);

Promise.resolve()
  .then(() => {
    console.log(4);
    setTimeout(() => console.log(5), 0);
  })
  .then(() => console.log(6));

(async () => {
  console.log(7);
  await null;
  console.log(8);
})();

console.log(9);

⌨️ Terminal

node puzzle.js

🖥️ Output

1
7
9
4
8
6
2
3
5
  1. Synchronous code: 1, then the async function runs until its first await: 7, then 9.
  2. Microtasks, in the order they were queued: the first .then logs 4 (and schedules timer 5); the code after await logs 8; the chained .then logs 6.
  3. Next task: the first timer logs 2 and queues a microtask, which runs right away: 3.
  4. Next task: the timer scheduled inside the promise logs 5.

💡 Tip: Code after await always continues as a microtask, even when the awaited value is not a promise (await null). That is why 8 comes after the synchronous 9.


⏱️ setTimeout(fn, 0) Is Not Instant

A timer’s delay is a minimum, not a guarantee. The callback runs only when its time has passed and the call stack is empty and all microtasks are done.

📄 delay.js

const start = Date.now();

setTimeout(() => {
  const waited = Date.now() - start;
  console.log(`timer asked for 10 ms, actually waited at least 200 ms: ${waited >= 200}`);
}, 10);

// Busy synchronous work for ~200 ms blocks the timer
while (Date.now() - start < 200) {}
console.log("busy loop finished");

⌨️ Terminal

node delay.js

🖥️ Output

busy loop finished
timer asked for 10 ms, actually waited at least 200 ms: true

⚠️ Watch out: Because delays are only minimums, fixed waits such as await page.waitForTimeout(2000) in tests are fragile: on a slow CI machine 2 seconds may not be enough, and on a fast one it wastes time. Wait for a condition instead (an element, a URL, a response), which is what Playwright’s auto-waiting and web-first assertions do.


Advertisement

🚦 process.nextTick, queueMicrotask and setImmediate (Node.js)

Node.js adds two scheduling functions of its own:

FunctionRuns
process.nextTick(fn)Before promise microtasks, as soon as the current operation finishes (Node.js only)
queueMicrotask(fn) / promise callbacksIn the microtask queue
setTimeout(fn, 0)In the timers phase of the next loop turn
setImmediate(fn)In the “check” phase, right after I/O callbacks (Node.js only)

📄 node-order.js

const fs = require("node:fs");

fs.readFile(__filename, () => {          // inside an I/O callback the order is predictable
  setTimeout(() => console.log("4. setTimeout"), 0);
  setImmediate(() => console.log("3. setImmediate"));
  Promise.resolve().then(() => console.log("2. promise"));
  process.nextTick(() => console.log("1. nextTick"));
});

⌨️ Terminal

node node-order.js

🖥️ Output

1. nextTick
2. promise
3. setImmediate
4. setTimeout

📌 Note: At the top level of a script, the order of setTimeout(fn, 0) and setImmediate(fn) is not guaranteed; it depends on how fast the process starts. Inside an I/O callback, as above, setImmediate always runs first. Do not write code that depends on this race.


🧊 Blocking the Event Loop

While synchronous code runs, nothing else can happen: no timers, no network callbacks, no clicks, no page rendering. In a browser the page freezes; in Node.js a server stops answering every user.

📄 blocking.js

let ticks = 0;
const interval = setInterval(() => ticks++, 10);   // should tick ~every 10 ms

setTimeout(() => {
  const start = Date.now();
  while (Date.now() - start < 300) {}               // 300 ms of blocking work
  console.log("blocking work done");
}, 0);

setTimeout(() => {
  clearInterval(interval);
  console.log(`ticks in ~400 ms: ${ticks} (would be about 40 without blocking)`);
  console.log("far fewer ticks than expected:", ticks < 20);
}, 400);

⌨️ Terminal

node blocking.js

🖥️ Output

blocking work done
ticks in ~400 ms: 7 (would be about 40 without blocking)
far fewer ticks than expected: true

Common causes of blocking: huge synchronous loops, JSON.parse of very large files, synchronous file APIs (fs.readFileSync) in servers, and heavy regular expressions. Fixes: use async APIs, split work into chunks, or move it to a worker thread.

Starving the loop with microtasks

Because the microtask queue is emptied completely before the next task, code that keeps adding microtasks forever starves timers just as badly as a busy loop. This is rare, but it is the reason a never-ending chain of .then calls can freeze a page.


🧪 Tester Scenario: Why a Missing await Makes Tests Flaky

A test function returns before the work it started has finished if that work is not awaited. The checks then run against stale state, or after the test is already reported as passed:

📄 missing-await.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));

const page = {
  heading: "Login",
  async clickLogin() {
    await delay(20);                 // navigation takes time
    this.heading = "Dashboard";
  },
};

async function flakyTest() {
  page.heading = "Login";
  page.clickLogin();                 // missing await!
  return page.heading === "Dashboard" ? "PASS" : `FAIL (heading is "${page.heading}")`;
}

async function correctTest() {
  page.heading = "Login";
  await page.clickLogin();           // waits for the navigation to finish
  return page.heading === "Dashboard" ? "PASS" : `FAIL (heading is "${page.heading}")`;
}

(async () => {
  console.log("without await:", await flakyTest());
  await delay(30);
  console.log("with await:   ", await correctTest());
})();

⌨️ Terminal

node missing-await.js

🖥️ Output

without await: FAIL (heading is "Login")
with await:    PASS

In a real test the “work” is a click, a navigation or an API call. If its result happens to arrive fast, the flaky version sometimes passes, which is exactly what makes these bugs hard to find. Playwright and ESLint (@typescript-eslint/no-floating-promises) can warn about promises that are not awaited.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Predict the output order, then run it.

setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
Show answer

📄 practice1.js

setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("sync");

🖥️ Output

sync
promise
timeout

Synchronous code first, then microtasks (the promise), then the next task (the timer).

Q2. Predict the output, then run it.

async function f() {
  console.log("a");
  await undefined;
  console.log("b");
}
f();
console.log("c");
Show answer

📄 practice2.js

async function f() {
  console.log("a");
  await undefined;
  console.log("b");
}
f();
console.log("c");

🖥️ Output

a
c
b

An async function runs synchronously until its first await; the rest continues as a microtask after the current synchronous code.

Q3. Show that two timers with the same delay run in the order they were scheduled, and that a 0 ms timer still runs after a microtask.

Show answer

📄 practice3.js

setTimeout(() => console.log("timer A"), 0);
setTimeout(() => console.log("timer B"), 0);
queueMicrotask(() => console.log("microtask"));
console.log("sync");

🖥️ Output

sync
microtask
timer A
timer B

Q4. Write a function that splits a long job (summing 1 to 3,000,000) into chunks of 1,000,000 with setTimeout between them, so the event loop can handle other work in between. Print the final sum.

Show answer

📄 practice4.js

function sumInChunks(n, chunk, done) {
  let total = 0, i = 1;
  function work() {
    const end = Math.min(i + chunk, n + 1);
    for (; i < end; i++) total += i;
    if (i <= n) setTimeout(work, 0);   // let other callbacks run
    else done(total);
  }
  work();
}
sumInChunks(3_000_000, 1_000_000, (total) => console.log("sum:", total));
setTimeout(() => console.log("another callback got a turn"), 0);

🖥️ Output

another callback got a turn
sum: 4500001500000

The “another callback” line runs between chunks, proving the loop was not blocked for the whole job.

Q5. Predict the output, then run it.

process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
Show answer

📄 practice5.js

process.nextTick(() => console.log("tick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");

🖥️ Output

sync
tick
promise

In Node.js, the process.nextTick queue runs before the promise microtask queue.

Q6. Explain in two sentences why await page.waitForTimeout(3000) is a poor way to wait for a slow page in a test, and what to use instead.

Show answer

A fixed delay is a guess: it is too short on a slow machine (flaky failures) and wastes time on a fast one, and timers only guarantee a minimum delay anyway. Wait for the actual condition instead, for example await expect(page.getByText("Dashboard")).toBeVisible() or await page.waitForURL("**/dashboard").


🧠 MCQ Quiz: Event Loop

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. How many pieces of your JavaScript code run at the same time on the main thread?
  2. When does a setTimeout(fn, 0) callback run?
  3. Which runs first?
  4. Which of these is a microtask?
  5. What happens to timers while a long synchronous loop runs?
  6. In Node.js, which runs before promise callbacks?
  7. What is printed?
    Promise.resolve().then(() => console.log("p"));
    console.log("s");
  8. Why is the order of top-level setTimeout(fn, 0) and setImmediate(fn) not guaranteed in Node.js?
  9. What can freeze a web page?
  10. Why can a missing await make a test pass sometimes and fail other times?

💼 Interview Questions and Answers

Q1. Explain the JavaScript event loop.

JavaScript executes code on one call stack. Asynchronous operations are delegated to the host environment (browser Web APIs or Node.js/libuv). When they complete, their callbacks are queued: promise reactions in the microtask queue, timers and I/O in task queues. The event loop takes the next task only when the call stack is empty, and after every task it drains the entire microtask queue. This lets a single thread handle many concurrent operations without blocking.

Q2. What is the difference between microtasks and macrotasks?

Microtasks (promise then/catch/finally, code after await, queueMicrotask, and process.nextTick in Node.js with higher priority) run right after the current task and are drained completely. Macrotasks (setTimeout, setInterval, I/O, UI events, setImmediate) run one per event-loop turn. So a resolved promise’s callback always runs before a setTimeout(fn, 0) scheduled at the same time.

Q3. Predict the output.

📄 interview-order.js

console.log("start");
setTimeout(() => console.log("timeout 1"), 0);
Promise.resolve().then(() => {
  console.log("promise 1");
  setTimeout(() => console.log("timeout 2"), 0);
}).then(() => console.log("promise 2"));
console.log("end");

⌨️ Terminal

node interview-order.js

🖥️ Output

start
end
promise 1
promise 2
timeout 1
timeout 2

Synchronous: start, end. Microtasks: promise 1 (which schedules timeout 2), promise 2. Tasks in scheduling order: timeout 1, timeout 2.

Q4. How does the event loop relate to flaky UI tests?

UI actions, network responses and rendering complete asynchronously at times that vary between runs and machines. Tests that check state without awaiting the operation (missing await) or that rely on fixed sleeps race against the event loop and pass or fail depending on timing. Reliable tests await every action and wait for observable conditions, which Playwright’s auto-waiting and retrying assertions are designed for.


Advertisement

❓ Frequently Asked Questions

🤔 Is JavaScript really single-threaded?

Your JavaScript code runs on one main thread. The runtime uses other threads for I/O, and you can create extra JavaScript threads explicitly with Web Workers or Node.js worker threads.

🤔 Is the event loop part of the JavaScript language?

The language defines jobs (microtasks) and promises; the full event loop with timers, I/O and rendering is provided by the host: the HTML specification for browsers and libuv for Node.js.

🤔 Why does my setTimeout run later than the delay I set?

Delays are minimums. The callback waits for the call stack to clear and all microtasks to finish, and browsers also clamp nested and background-tab timers.

🤔 Does await block the whole program?

No. It pauses only the current async function; the event loop keeps running other code until the awaited promise settles.


🏁 Summary

  • JavaScript runs one call stack; slow work happens in the runtime, and callbacks are queued for later.
  • The event loop runs a task, then drains all microtasks, then takes the next task.
  • Promise callbacks and code after await are microtasks; timers and I/O are tasks, so promises run first.
  • Timer delays are minimums; long synchronous code blocks timers, I/O and rendering.
  • In tests, await every async action and wait for conditions instead of fixed delays.

Next, continue with Lesson 47: Callbacks and Timers.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in