Loading
Portfolio
Rayden Li
Node.js · JavaScript
JavaScript often looks as if several things happen at once: a timer finishes, a network response arrives, and a Promise resolves. On a browser's main thread, however, JavaScript normally runs one piece of code at a time. The event loop decides which piece gets its turn next.
The most useful rule to remember is:
Run the current task and its synchronous code, drain every microtask, possibly render, and then run the next task.
This article builds that rule from the ground up and then tests it with runnable examples.
The call stack tracks the JavaScript that is executing now. Calling a function adds its execution context to the stack; returning removes it. Only the item at the top can run.
function greet() {
console.log("Hello");
}
greet();
The script starts, greet() is pushed onto the stack, console.log() runs, and greet() returns. This is all synchronous.
The ECMAScript specification describes this more precisely as a stack of execution contexts.
A task is a unit of work such as:
setTimeout() callback."Macrotask" is common teaching terminology used to contrast these with microtasks. It is not the term used by the HTML Standard; the standard calls them tasks. It also allows an event loop to have multiple task queues, rather than requiring one universal FIFO queue. Tasks from the same source keep their required order, while the browser can choose between task queues. See the HTML Standard's definitions of event loops and task queues.
A microtask is deferred work that runs at a microtask checkpoint, before the browser moves on to another task. Common sources are:
Promise.prototype.then(), .catch(), or .finally();await; andqueueMicrotask().ECMAScript specifies Promise reactions as jobs, and HTML maps Promise jobs onto its microtask queue. The relevant specifications are ECMAScript Promise reaction jobs and HTML's HostEnqueuePromiseJob.
The important difference is that the microtask queue is drained completely. If one microtask adds another, the new one also runs before the next task. This behavior is defined by HTML's microtask checkpoint algorithm.
For browser JavaScript, this simplified cycle is accurate enough for everyday reasoning:
The task-then-checkpoint order comes from the HTML event loop processing model. Rendering is conditional: a browser does not have to paint after every task. Its rules for rendering opportunities are described under updating the rendering.
Browser-only behavior: rendering and painting belong to the browser model. Node.js has an event loop but no browser rendering step.
setTimeout, Promise, and queueMicrotaskRun this in a browser console or with Node.js:
console.log("script start");
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
queueMicrotask(() => console.log("queueMicrotask"));
console.log("script end");
Exact output:
script start
script end
promise
queueMicrotask
timeout
Here is the execution trace:
| Step | Running code | Task queue state | Microtask queue state | Output added |
|---|---|---|---|---|
| 1 | Initial script starts | Empty | Empty | script start |
| 2 | setTimeout(...) | Timer task will become runnable | Empty | — |
| 3 | Promise.resolve().then(...) | Timer pending | Promise reaction | — |
| 4 | queueMicrotask(...) | Timer pending | Promise reaction, then queueMicrotask callback | — |
| 5 | Initial script finishes | Timer pending | Both microtasks waiting | script end |
| 6 | Microtask checkpoint | Timer pending | queueMicrotask callback remains | promise |
| 7 | Microtask checkpoint continues |
Why does "promise" come before "queueMicrotask"? The already-resolved Promise queues its reaction first. queueMicrotask() is called afterward, so its callback goes behind that reaction in the same microtask queue.
Why is the zero-delay timer last? Zero milliseconds is a delay threshold, not permission to interrupt the current task. The callback can run only when the host schedules its task. The HTML specification defines this behavior in the timer initialization steps.
console.log("script");
setTimeout(() => {
console.log("timer 1");
queueMicrotask(() => console.log("microtask in timer 1"));
setTimeout(() => console.log("timer 3"), 0);
}, 0);
setTimeout(() => console.log("timer 2"), 0);
queueMicrotask(() => {
console.log("microtask 1");
queueMicrotask(() => console.log("nested microtask"));
});
Exact output:
script
microtask 1
nested microtask
timer 1
microtask in timer 1
timer 2
timer 3
Two details explain the result:
microtask 1 adds nested microtask. The checkpoint does not stop, so the nested microtask runs before any timer.timer 1 finishes, another checkpoint runs immediately. Therefore microtask in timer 1 runs before timer 2. timer 3 was registered later and runs after the earlier timers.This is why microtasks are useful for small follow-up operations that must happen before external events get another turn.
async/await also uses microtasksasync function demo() {
console.log("inside: before await");
await 0;
console.log("inside: after await");
}
console.log("script: start");
demo();
Promise.resolve().then(() => console.log("promise callback"));
console.log("script: end");
Exact output:
script: start
inside: before await
script: end
inside: after await
promise callback
An async function runs synchronously until it reaches await. It then suspends, and its continuation is scheduled through Promise machinery. Even await 0 yields: the code after it does not continue on the current stack. In this example, that continuation is queued before the later .then() callback, so it runs first. See ECMAScript's Await operation.
Because a checkpoint must keep draining newly queued microtasks, an endless chain can prevent timers, input handling, and browser rendering from getting a turn. This safe example stops after five iterations:
let remaining = 5;
setTimeout(() => console.log("timer"), 0);
function repeat() {
console.log("microtask " + (6 - remaining));
remaining -= 1;
if (remaining > 0) {
queueMicrotask(repeat);
}
}
queueMicrotask(repeat);
console.log("script end");
Exact output:
script end
microtask 1
microtask 2
microtask 3
microtask 4
microtask 5
timer
If repeat() always queued itself, the microtask queue would never become empty and the timer would not run. Do not try the unbounded version in a production page.
It does not. setTimeout(fn, 0) schedules fn for a future task after the delay requirements are satisfied. Current synchronous code and all pending microtasks still run first.
Creating a Promise does not create a thread. The Promise executor runs synchronously. Its reaction callbacks are scheduled as jobs that browsers process as microtasks. Separate browser APIs may perform work outside the JavaScript thread, but their JavaScript callbacks still need a scheduled turn.
There are different scheduling mechanisms. HTML formally permits multiple task queues and defines a separate microtask queue. Treating everything as one queue produces incorrect output predictions.
Rendering happens only when the browser has a rendering opportunity. A long task or an endlessly refilled microtask queue can delay visible updates.
Microtasks have higher scheduling priority relative to the next task, but that does not make expensive work cheap. Heavy work in a microtask still blocks the main thread.
async/await to express dependencies between asynchronous operations.queueMicrotask() only for short consistency or cleanup work that must happen after the current stack but before the next task.The examples above produce the shown output in modern browsers and Node.js, but their host event loops are not identical.
Browsers use the HTML task/microtask model and may render between turns. Node.js uses libuv phases such as timers, poll, and check; setImmediate() is also Node-specific. Node additionally has a process.nextTick() queue with behavior separate from the standard microtask queue. The Node documentation recommends queueMicrotask() for most portable userland deferral and explains CommonJS-versus-ES-module ordering details in When to use queueMicrotask() vs. process.nextTick().
For server-side scheduling questions, use Node's own event loop guide instead of assuming every browser rule maps directly to Node.
When asked what a snippet prints:
In short: synchronous code first, then all microtasks, then the next task.
| Timer pending |
| Empty |
queueMicrotask |
| 8 | Next eligible timer task runs | Empty | Empty | timeout |