# The Event Loop

> Understand how single-threaded JavaScript handles asynchronous tasks using the Call Stack, Web APIs, and the Microtask Queue.

Subject: JavaScript | Lesson 30 of 63 | 9 min read
Interactive lesson: https://codewithanimation.in/javascript/event-loop
Previous: [JSON: parse & stringify](https://codewithanimation.in/javascript/json.md) | Next: [Callbacks & Callback Hell](https://codewithanimation.in/javascript/callbacks-and-async-history.md)

## The Single-Threaded Illusion

JavaScript is strictly single-threaded, meaning it can only execute one piece of code at a time on its main thread.

To prevent the browser from freezing during slow tasks (like fetching data), JavaScript offloads work to the browser's background APIs, orchestrating the results via the Event Loop.

## The Call Stack (LIFO)

The **Call Stack** is where your synchronous code actually runs. It operates on a 'Last In, First Out' (LIFO) principle.

If `function A` calls `function B`, `A` is paused and `B` is placed on top of the stack. When `B` finishes, it pops off, and `A` resumes.

If the Call Stack is busy, *nothing else can happen*. The browser cannot even render pixels until the stack is empty.

## The Queues: Micro vs Macro

When a background task finishes, its callback isn't executed immediately. It is pushed into a waiting line. There are two distinct lines:

1. **The Microtask Queue**: Reserved for high-priority tasks, primarily resolved Promises (`.then`).

2. **The Macrotask Queue**: Reserved for standard callbacks like `setTimeout`, `setInterval`, and DOM events.

The Event Loop's only job is to watch the Call Stack. If the Stack is empty, it drains the *entire* Microtask queue first. Only when the Microtask queue is empty will it allow a Macrotask to run.

## Common mistake: The setTimeout(0) Trick

Sometimes you'll see code wrapped in `setTimeout(() => { ... }, 0)`. Why wait 0 milliseconds? It is a trick to intentionally push a heavy piece of code to the back of the Macrotask Queue. This allows the Call Stack to clear, giving the browser a split second to breathe and render the UI before tackling the heavy task.

## Tip: Microtasks always jump the line

If a Promise resolves at the exact same millisecond that a `setTimeout` timer finishes, the Promise's `.then()` callback will ALWAYS execute first. Microtasks have absolute priority.

## Try it: The Loop Architecture

Examine the architecture of the Event Loop to visualize how synchronous code, Web APIs, and priority queues interact.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/event-loop

## Check yourself

### Question 1

What happens if a function on the Call Stack takes 10 seconds to execute?

- A. The browser freezes completely for 10 seconds because the main thread is blocked.
- B. The Event Loop moves it to the background to keep the UI responsive.
- C. It throws a Timeout Error after 5 seconds.

Correct answer: A

Because JS is single-threaded, a slow synchronous function blocks the Call Stack. If the Stack is blocked, the browser cannot render or process clicks.

- Why not B: Incorrect. The Event Loop cannot move running code off the stack.
- Why not C: Incorrect. While browsers may show an 'Unresponsive Script' warning eventually, the technical truth is the main thread is fully blocked.

### Question 2

Which queue has priority when the Call Stack becomes empty?

- A. The Microtask Queue
- B. The Macrotask Queue
- C. Whichever task arrived first (FIFO)

Correct answer: A

The Event Loop will always completely drain the Microtask Queue (Promises) before it looks at the Macrotask Queue.

- Why not B: Incorrect. Macrotasks (like setTimeout) must wait for Microtasks.
- Why not C: Incorrect. Queue priority overrides arrival time.

### Question 3

If you call `setTimeout(callback, 1000)`, where does the countdown happen?

- A. Inside the Browser's Web APIs
- B. On the Call Stack
- C. In the Macrotask Queue

Correct answer: A

JavaScript hands the timer off to the browser's background Web APIs. When the browser finishes counting to 1000, it pushes the callback into the queue.

- Why not B: Incorrect. If it happened on the stack, the browser would be frozen for 1 second.
- Why not C: Incorrect. The Queue just holds the callback *after* the timer finishes.

## Remember this

- JavaScript is single-threaded and executes synchronously on the Call Stack.
- Background work (timers, network requests) is offloaded to the browser's Web APIs.
- Resolved Promises go to the high-priority Microtask Queue.
- `setTimeout` and DOM events go to the lower-priority Macrotask Queue.
- The Event Loop only pulls from the queues when the Call Stack is completely empty.
- The Event Loop always drains the Microtask Queue entirely before running a Macrotask.
