...
Sign in

How JavaScript Works: Execution Context & The Event Loop

Master the JavaScript runtime: uncover how single-threaded JavaScript handles non-blocking asynchronous operations using the Call Stack, Web APIs, Microtask Queue, and the Event Loop.

Share:

How JavaScript Works: Execution Context & The Event Loop

JavaScript is famously described as a single-threaded, non-blocking, asynchronous, concurrent runtime.

At first glance, this sounds like a contradiction:

  • If JavaScript is single-threaded, it has only one Call Stack and can do only one thing at a time.
  • If it can only do one thing at a time, why doesn't your web page freeze whenever you fetch data from a server or set a timer?

The answer lies in the JavaScript Runtime Architecture and its central conductor: The Event Loop.


1. The Core Architecture: Engine vs. Runtime

When you run JavaScript in a browser (like Chrome or Brave) or on a server (like Node.js), JavaScript code does not live in isolation.

┌─────────────────────────────────────────────────────────────┐
│                      JavaScript Runtime                     │
│                                                             │
│  ┌─────────────────────────┐     ┌───────────────────────┐  │
│  │     JS Engine (V8)      │     │    Web APIs / Node    │  │
│  │ ┌─────────┐ ┌─────────┐ │     │ ┌───────────────────┐ │  │
│  │ │ Memory  │ │  Call   │ │     │ │ DOM / fetch() /   │ │  │
│  │ │  Heap   │ │  Stack  │ │     │ │ setTimeout()      │ │  │
│  │ └─────────┘ └─────────┘ │     │ └───────────────────┘ │  │
│  └─────────────────────────┘     └───────────┬───────────┘  │
│                                              │              │
│               ┌──────────────────────────────┘              │
│               ▼                                             │
│  ┌─────────────────────────┐     ┌───────────────────────┐  │
│  │     Microtask Queue     │     │    Macrotask Queue    │  │
│  │ (Promises / VIP queue)  │     │   (Timers / Events)   │  │
│  └────────────┬────────────┘     └───────────┬───────────┘  │
│               │                              │              │
│               └──────────────┬───────────────┘              │
│                              ▼                              │
│                    ┌──────────────────┐                     │
│                    │    EVENT LOOP    │                     │
│                    └──────────────────┘                     │
└─────────────────────────────────────────────────────────────┘

1. Memory Heap

Where memory allocation happens. Objects, variables, and arrays you declare are allocated here in memory.

2. Call Stack (LIFO: Last In, First Out)

The execution stack. Every time a function is invoked, an Execution Context is pushed onto the stack. When the function returns, its frame is popped off. Because JavaScript has only one Call Stack, it can only execute one line of code at any given microsecond.

3. Web APIs / C++ Background Threads

Features provided by the host environment (Browser or Node.js), not the JS engine itself:

  • setTimeout() and setInterval()
  • fetch() and XMLHttpRequest
  • DOM events (addEventListener)

When you call setTimeout, the JS engine offloads the timer countdown to the host environment's background threads, keeping the Call Stack unblocked!


2. Interactive Event Loop & Call Stack Stepper

Step through classic asynchronous execution orders in real-time. Watch how the engine moves tasks between the Call Stack, Web APIs, Microtask Queue, and Macrotask Queue.

Event Loop & Asynchronous Runtime Stepper

V8 Architecture

Watch the Call Stack, Web APIs, Microtask (VIP) Queue, and Macrotask Queue interact step-by-step.

0
Step 0 of 10

Initial state: Script is loaded. Call stack, queues, and console are clean.

JavaScript ScriptSource
console.log("1");

setTimeout(() => {
  console.log("2");
}, 0);

Promise.resolve().then(() => {
  console.log("3");
});

console.log("4");
Expected Output:[1, 4, 3, 2]
Call Stack (LIFO)
1 frame(s)
global()
Web APIs / Node Runtime
Background
(No active timers/requests)
Microtask Queue (VIP Priority)
Promises
(Queue empty)
Macrotask Queue (Task Queue)
setTimeout / I/O
(Queue empty)
Standard Console Output (stdout)
0 line(s)
// No output logged yet...
The Event Loop Algorithm in 3 Steps:
  1. Execute synchronous code in the Call Stack until it is completely empty.
  2. Drain all pending callbacks in the Microtask Queue (Promises, queueMicrotask) before touching anything else.
  3. Pick one task from the Macrotask Queue (setTimeout, I/O) and push it to the Call Stack. Repeat!

3. Microtasks vs. Macrotasks: The Priority Duel

Not all asynchronous callbacks are treated equally. The runtime splits callbacks into two queues with strict priority rules:

1. The Microtask Queue (VIP Priority)

  • Sources: Promises (.then(), .catch(), .finally()), async/await resumptions, and queueMicrotask().
  • Behavior: The Event Loop will completely drain the Microtask Queue before touching any Macrotask. If microtasks enqueue more microtasks, they will all execute before the browser paints or runs any timer!

2. The Macrotask Queue (Task Queue)

  • Sources: setTimeout(), setInterval(), setImmediate() (Node.js), and I/O callbacks.
  • Behavior: The Event Loop processes only one macrotask per tick, then immediately checks if new microtasks appeared.

4. The Famous Interview Puzzle: Can You Predict the Output?

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

Step-by-Step Breakdown:

  1. console.log("1") runs synchronously →\rightarrow Prints 1.
  2. setTimeout(..., 0) registers a timer in Web APIs. The 0ms timer expires immediately and places console.log("2") in the Macrotask Queue.
  3. Promise.resolve().then(...) creates a resolved promise and enqueues console.log("3") in the Microtask Queue.
  4. console.log("4") runs synchronously →\rightarrow Prints 4.
  5. The Call Stack is now empty! The Event Loop checks the Microtask Queue first →\rightarrow Prints 3.
  6. Microtask queue is empty. The Event Loop takes the first item from the Macrotask Queue→\rightarrow Prints 2.

Final Output:

1
4
3
2

[!IMPORTANT] Why setTimeout(..., 0) is not instantaneous: Setting a timeout delay to 0 does not mean "execute immediately". It means "register a timer that expires in 0ms, and place its callback in the Task Queue". The callback will only run after all synchronous code and all pending microtasks have finished!


5. Flashcards & Core Concepts

Active Recall
Card

Why is JavaScript called 'single-threaded'?

Click or Press Space to Flip
Key Takeaway
Because it has only one Call Stack, meaning it can only execute a single instruction or function at any given moment in the main thread.
Click to Flip Back
Active Recall
Card

Which has higher priority: the Microtask Queue or the Macrotask Queue?

Click or Press Space to Flip
Key Takeaway
The Microtask Queue (Promises, queueMicrotask) always takes priority. The Event Loop must completely drain all microtasks before picking the next macrotask.
Click to Flip Back

6. Knowledge Check

CheckpointCheckpoint
Question 1 of 3Score: 0/3

Where does the callback of a resolved Promise (.then) get placed?

Lesson Milestone

Finished Reading This Lesson?

Mark this lesson complete. A chapter counts as done once all its lessons are, and that adds to your course progress.

TH

Written by

ThinkWisely Team

Have a Question or Suggestion?

We'd love to hear from you. Drop your thoughts below to help us improve ThinkWisely!