Microtask vs Macrotask: Why Promises Jump the Queue in JavaScript
# Microtask vs Macrotask: Why Promises Jump the Queue in JavaScript
Run this code and predict the output before you read on:
```js
console.log("1. Sync code");
setTimeout(() => console.log("2. Timer"), 0);
Promise.resolve().then(() => console.log("3. Promise"));
console.log("4. More sync code");
```
The output is:
```
1. Sync code
4. More sync code
3. Promise
2. Timer
```
The timer was scheduled first, with a delay of zero — yet the promise runs before it. This is not a quirk or a bug. It is the event loop working exactly as designed, and the reason is that JavaScript has **two different queues**: a macrotask queue and a microtask queue. Promises live in the fast lane, and understanding which lane a piece of work is in explains a surprising amount of asynchronous behaviour.
At Ovlyc, this is one of the first things we explain when a developer is confused by the order of async code in a real project — because once you know the two queues, the order stops feeling random.
## The Two Queues, in Plain Terms
When JavaScript finishes a piece of synchronous code, the event loop looks for the next thing to run. It does not pick from a single line. It checks two lines, in a strict order:
**1. The macrotask queue (also called the task queue)**
This is the general queue. Each item here is a macrotask — a whole unit of work, such as a timer callback, a user event handler, a `fetch` completion, or a script itself. The event loop runs **one macrotask**, then stops and checks the other queue before running the next one.
**2. The microtask queue**
This is the priority lane. It holds small, quick follow-up work: promise callbacks (`.then`, `.catch`, `.finally`), `queueMicrotask` callbacks, and `MutationObserver` callbacks. After every macrotask — and after every single microtask — the event loop empties the **entire** microtask queue before it touches the next macrotask.
That rule is the whole story: **one macrotask at a time, but all pending microtasks in between.** A microtask can even schedule another microtask, and that new one runs before the loop moves on. The loop only returns to macrotasks when the microtask queue is completely empty.
## Which API Goes Where
| Goes to the microtask queue | Goes to the macrotask queue |
|---|---|
| `Promise.then / .catch / .finally` | `setTimeout` / `setInterval` |
| `queueMicrotask()` | `setImmediate` (Node.js) |
| `MutationObserver` callbacks | User events (click, input, scroll) |
| `async` function continuations after `await` | I/O callbacks, network responses |
| `process.nextTick` (Node.js — its own even-faster lane) | `requestAnimationFrame` (browser, before paint) |
The most important row is the first one. Almost every modern JavaScript application is built on promises — `fetch`, database calls, file reads — so promise callbacks are the microtasks you will meet most often.
## A Step-by-Step Walkthrough
Let us trace the opening example, line by line:
```js
console.log("1. Sync code");
setTimeout(() => console.log("2. Timer"), 0);
Promise.resolve().then(() => console.log("3. Promise"));
console.log("4. More sync code");
```
1. The script itself is a macrotask, running on the call stack. `console.log("1. Sync code")` prints immediately.
2. `setTimeout` schedules a timer callback. It goes into the **macrotask queue**. The timer expires almost immediately, but the callback still has to wait its turn.
3. `Promise.resolve().then(...)` schedules a promise callback. It goes into the **microtask queue**.
4. `console.log("4. More sync code")` prints. The script finishes and the stack empties.
5. The event loop now checks the microtask queue first. It finds the promise callback and runs it: `3. Promise` prints.
6. Only when the microtask queue is empty does the loop take the next macrotask: the timer callback runs and `2. Timer` prints.
The timer was scheduled before the promise, but the queues do not care about scheduling order across lanes. Microtasks always drain first.
## Microtasks Can Queue More Microtasks
A microtask that creates another microtask does not wait for the next round. It jumps straight in:
```js
Promise.resolve().then(() => {
console.log("First promise");
Promise.resolve().then(() => {
console.log("Second promise");
});
});
setTimeout(() => console.log("Timer"), 0);
// Output:
// First promise
// Second promise
// Timer
```
The second promise callback was created while the first was running, and it still runs before the timer. The loop keeps draining microtasks until the queue is empty — there is no limit on how many times it can refill in one cycle.
This leads to the one real danger of microtasks: **microtask starvation**. If microtasks keep scheduling new microtasks forever, the event loop never gets back to macrotasks. Timers never fire, clicks never get handled, the UI never repaints. In practice this usually comes from a recursive promise chain that never ends:
```js
// Do not do this — it starves the event loop
function loopForever() {
Promise.resolve().then(loopForever);
}
loopForever();
```
The browser tab will freeze even though nothing is "blocking" in the traditional sense. The fix is simple: if a repeating job does not need to be immediate, use `setTimeout` so each iteration becomes a macrotask and the loop gets a chance to breathe.
## `queueMicrotask`: Scheduling Work Yourself
Sometimes you want a piece of work to run after the current synchronous code finishes, but before any timer or event. That is exactly what `queueMicrotask` is for:
```js
console.log("Start");
queueMicrotask(() => console.log("Microtask runs next"));
setTimeout(() => console.log("Timer runs last"), 0);
console.log("End");
// Output:
// Start
// End
// Microtask runs next
// Timer runs last
```
This is useful for deferring a small, non-urgent step — finishing a cleanup, notifying a listener, batching a state update — without paying the cost of a timer. At Ovlyc, we use it in places where a callback must run "right after this function, but not right now": for example, flushing a batched UI update after a synchronous state change, before the browser has a chance to repaint with stale data.
## `async` / `await` Is Microtask Sugar
An `async` function looks synchronous, but every `await` is a microtask boundary:
```js
async function demo() {
console.log("A");
await Promise.resolve();
console.log("B");
}
demo();
console.log("C");
// Output:
// A
// C
// B
```
`await Promise.resolve()` pauses the function and schedules the rest of it as a microtask. The synchronous code after the call (`C`) runs first, and `B` follows once the microtask queue drains. This is why `await` inside a loop still lets other synchronous code interleave — each `await` is a handoff to the microtask queue, not a block.
## Why This Matters When You Build Products
The two-queue model is not academic trivia. It shows up in real bugs:
- **UI updates that seem to happen "late".** If you update the DOM inside a promise chain, the update happens before the next timer — but after all currently running synchronous code. Knowing this tells you whether a render will happen before or after a repaint.
- **A promise chain that starves rendering.** A long chain of `.then()` calls keeps the microtask queue full, so the browser cannot paint between them. Breaking the chain with `setTimeout` or `requestAnimationFrame` gives the browser a chance to draw.
- **Timers that fire later than expected.** A timer callback is a macrotask. If a flood of microtasks is draining, the timer waits — even if its delay expired long ago. `setTimeout(fn, 0)` means "as soon as possible after the microtasks clear", never "right now".
- **Order-dependent logic in tests.** Tests that mix timers and promises fail intermittently when the author assumes scheduling order equals execution order. The queue, not the clock, decides.
The practical rule is short: **use microtasks for quick follow-ups that must happen soon, and macrotasks for work that can wait its turn.** Promise callbacks are the natural microtask — they continue a chain of async work. Timers and events are the natural macrotask — they respond to the outside world.
## The Big Picture
JavaScript's event loop runs one macrotask at a time, and after each one it drains the entire microtask queue before moving on. Promise callbacks, `queueMicrotask`, and `await` continuations live in the microtask lane, so they always run before timer callbacks and event handlers that were scheduled earlier. That is why the promise in our first example beat the zero-delay timer — and why a chain of promises can delay a timer indefinitely.
One thread, two queues, one rule: microtasks first, always. Keep that rule in mind and the execution order of async JavaScript stops being a mystery — it becomes something you can predict, line by line.
In the next article, we will step back from the queues and look at execution context — the environment JavaScript creates every time a function runs, and where variables actually live while your code executes.
Related Articles
What Is Node.js? JavaScript Beyond the Browser
Learn what Node.js is, how its V8 engine, libuv, and event loop work, and when to use it for APIs, real-time apps, and full-stack JavaScript.
Execution Context: Where JavaScript Variables Actually Live
Learn how JavaScript execution contexts work — the creation and execution phases, hoisting, the scope chain, closures, and how this is decided.
Explain the JavaScript Event Loop: How One Thread Handles Everything
How JavaScript's single thread stays responsive: the call stack, callback and microtask queues, timers, and why blocking the loop freezes everything.
Call Stack + Heap + Memory: How JavaScript Stores and Runs Your Code
Learn how JavaScript's call stack and heap work together — why recursion overflows, why objects share references, and where memory leaks come from.