---
title: "Event Loop & Microtasks"
description: "Follow browser callbacks through the stack, queues, and microtask checkpoints."
source: https://vizlearn.app/cs/runtime/event-loop-microtasks
---

# Event Loop & Microtasks

The browser event loop makes even a zero-delay timer wait while synchronous code and a microtask
checkpoint finish. In this example, that checkpoint also runs microtasks added during the drain.
The timer was registered first, yet runs last: becoming ready does not give it permission to
interrupt the work ahead.

The surprising part is the word *empty*. The browser does not take a photograph of the queue
and process only the callbacks in that picture. It keeps checking the queue. A callback can
leave another callback behind, and that new arrival still gets a turn before the next task.

Suppose several synchronous updates need one small follow-up before another task starts.
A microtask can do that final work. If the follow-up keeps queuing more microtasks, however,
other tasks cannot get a turn until the checkpoint finishes. This is the decision the animation
helps you make: finish a small follow-up now, or let other tasks have an execution opportunity.

## How the Event Loop Drains Microtasks

The call stack holds the JavaScript currently executing. Registering a callback does not put
that callback on the stack. `setTimeout` registers a timer with the host; once eligible, its
callback can be queued as a timer task. A reaction attached with `.then()` to an already fulfilled
Promise is scheduled as a microtask. `queueMicrotask` also appends a microtask.

When the initial script returns, the following checkpoint removes the oldest microtask and
runs it. If that callback appends more work, the new work joins the tail. The checkpoint checks
again after the callback returns. It finishes only when the microtask queue is empty.

There are two separate guarantees here: queued callbacks do not interrupt the synchronous
script, and a checkpoint drains microtasks before the next task. Neither says that Promise
callbacks always beat every timer in every program. Registration and Promise settlement still
determine when work becomes eligible.

## Event Loop & Microtasks Step by Step

Run this as a classic script in a browser page. It is the lesson's default workload:

```javascript
function work() {
  console.log("P");
  queueMicrotask(() => console.log("N1"));
}

console.log("A");
setTimeout(() => console.log("T"), 0);
Promise.resolve().then(work);
queueMicrotask(() => console.log("Q1"));
console.log("B");
```

1. The script logs `A` and registers timer `T`. The animation then shows a possible host event:
   `T` becomes ready while the script is still running. It waits in the timer task queue.
2. The fulfilled Promise queues `P`; `queueMicrotask` queues `Q1` behind it. Neither callback
   runs yet. The microtask queue is `[P, Q1]`.
3. The script logs `B`, then returns. The stack empties and checkpoint 1 opens.
4. `P` leaves the queue and runs. It logs `P`, then appends `N1`. The queue is now `[Q1, N1]`.
   `P` returns; checkpoint 1 stays open.
5. `Q1` runs and logs `Q1`. Then `N1` runs and logs `N1`. The queue is already empty while `N1`
   runs, but the checkpoint must wait for that callback to return. Only then can it check the
   empty queue and close. Each callback returns before the next one starts.
6. Ready timer `T` can now run. It logs `T`, returns, and is followed by an empty checkpoint.
   That checkpoint finishes without inventing another callback.

The output is **A → B → P → Q1 → N1 → T**. Watch the checkpoint marker stay in place while
different callback cards visit the stack. `N1` joins behind `Q1`, but ahead of the waiting
timer's opportunity to execute.

## Why Does a Zero-Delay Timer Wait?

Zero is the requested delay, not permission to interrupt JavaScript. A timer must become
eligible and then be selected. The animation separates registration, readiness, and dispatch
so you can see which condition has been satisfied.

Choose **Same callback, timer**. Only replace `Promise.resolve().then(work)` with
`setTimeout(work, 0)`; the body of `work` stays unchanged. `Q1` drains after the script. The two
timer callbacks run in registration order, `T` then `P`. `P` creates `N1`, which runs in the
checkpoint after `P` returns. The output becomes **A → B → Q1 → T → P → N1**.

After a run finishes, **Compare with a timer** changes only P's scheduling while retaining
the completed output. Press Play to reveal the second result alongside it. Both microtask
counts stay fixed, so you can attribute the difference to the scheduling API.

In **Long microtask chain**, `N1` through `N6` keep `T` waiting. The example's explicit
stopping condition ends the chain. Without one, a
continually replenished queue could prevent other tasks and rendering from making progress.

## Event Loop Edge Cases

- With zero nested microtasks, `P` adds nothing. The default then outputs `A B P Q1 T`.
- With four sibling microtasks, all four stay ahead of `N1`. New arrivals join the tail.
- **Empty checkpoints** uses two timers and no microtasks. It outputs `A B T P`; empty drains
  still occur after the script and after each timer callback.
- The longest supported chain has six callbacks. This is a visualization input bound, not a
  browser queue capacity or a runtime recursion limit.

## Event Loop Common Mistakes

- Treating `setTimeout(fn, 0)` as a synchronous call to `fn`.
- Placing `N1` ahead of an already queued `Q1` because it was created inside `P`.
- Draining only the queue's original length and leaving newly appended microtasks for later.
- Assuming that every Promise-related operation is asynchronous. This example queues a
  reaction on a fulfilled Promise; a Promise constructor's executor runs synchronously.
- Assuming that a completed checkpoint guarantees a paint. It allows progress toward other
  work; the browser still decides whether a rendering opportunity produces an update.

## A Note on Simplification

This is one browser window event loop with a classic script and timer-source tasks. Browsers
can have multiple task queues; the drawing does not assert a global FIFO across their sources.
Timer readiness is schematic, and animation seconds are not browser milliseconds. Native API
frames, other checkpoint sites, Promise rejection handling, nested timer clamping, rendering
internals, and Node.js scheduling are omitted. No actual paint is simulated.

The scheduling rules follow the [HTML event-loop model](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model)
and [timer and microtask APIs](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html).
For the synchronous part, start with [Execution Trace](https://vizlearn.app/foundations/execution-model/execution-trace).
[Process Scheduling](https://vizlearn.app/cs/os/process-scheduling) teaches a different scheduler: which process
gets CPU time, rather than which browser callback may start.
