How JavaScript Actually Runs Engines Stack and Event Loop
How JavaScript runs on Node.js 24: the engine pipeline, the call stack, the heap, microtasks, timers and the event loop phases, with output for every example.

A JavaScript program looks like a list of statements, and it behaves like a list of statements until the first timer, the first promise or the first network call. Then the order of the output stops matching the order of the file, and the explanations people offer, "it is asynchronous", "it goes to the queue", "JavaScript is single threaded", are true and too short to predict anything. This guide builds the model from the bottom: what the engine does with your source, what the call stack is, where objects live, and how the event loop decides what runs next, in Node.js 24 first and in the browser where the two differ. Every example has its exact output, so you can check your own reading of the code against it.
The model has five parts, and each section below takes one. An engine turns text into running machine code. A call stack records which function is running and which called it. A heap holds the objects. A set of queues holds work that is waiting for the stack to be empty. An event loop moves work from the queues onto the stack, one piece at a time. JavaScript the language defines the first three and the shape of promise jobs. The host, which is Node.js, a browser, Deno or Bun, supplies timers, I/O and the loop itself, which is why the details differ between them while the core rules do not. If the split between language and host is new, what JavaScript and ECMAScript are draws that line first.
One thread, run to completion
JavaScript code in one realm runs on one thread, and a function that has started runs until it returns or throws. Nothing interrupts it to run another function in the same program. That rule is called run to completion, and it is the reason most JavaScript needs no locks: two callbacks can never modify the same variable at the same instant, because they never run at the same instant.
let balance = 100;
function withdraw(amount) {
const before = balance;
balance = before - amount;
console.log(`withdrew ${amount}, balance ${balance}`);
}
setTimeout(() => withdraw(30), 0);
setTimeout(() => withdraw(50), 0);withdrew 30, balance 70
withdrew 50, balance 20Each callback reads and writes balance without another callback running in the middle, so the result is the same on every run. The price of the guarantee is that a callback that takes a long time blocks everything else in that thread: other timers, incoming requests and, in a browser, painting. Most of the later sections are about that price.
The thread is not the whole process. Node.js has a pool of native threads for file system calls, DNS lookups and some crypto, and browsers run networking and rendering on other threads. Those threads do work in parallel and report back by putting a callback in a queue. Your JavaScript never runs on them. Parallel JavaScript exists too, as worker threads in Node.js and Web Workers in browsers, and each worker is a separate realm with its own stack, heap and event loop. The section on workers covers how they talk to each other.
What the engine does with your source
An engine is the program that reads JavaScript and runs it. V8 powers Chrome, Node.js and Deno, SpiderMonkey powers Firefox and JavaScriptCore powers Safari and Bun. They differ in internals and agree on the language, which is what the comparison of V8, SpiderMonkey and JavaScriptCore shows. The steps below describe V8 as shipped in Node.js 24, and the other engines follow the same outline with different names for the stages.
Parse. The source text becomes a syntax tree. A syntax error stops here, before any code has run, which is why a file with a typo on its last line prints nothing at all.
Compile to bytecode. An interpreter called Ignition turns each function into compact bytecode and runs it. V8 compiles a function lazily, the first time it is called, so a large library that you load and barely use costs little to start.
Collect feedback. While the bytecode runs, the engine records what types it sees at each operation: which object shapes reach a property read, whether an addition always sees small integers.
Compile hot code to machine code. A function that runs often is handed to faster compilers. V8 has a quick baseline compiler, Sparkplug, a mid-tier optimizing compiler, Maglev, and a top-tier optimizing compiler, TurboFan. The optimizers use the recorded feedback to generate machine code that assumes the types will stay the same.
Deoptimize on a wrong guess. If a function optimized for integers is called with a string, the machine code is thrown away and execution continues in the interpreter. The function can be optimized again later with the new feedback.
None of this changes what your program means. The language defines the result, and the engine is free to reach it any way that produces the same observable behavior. It matters for two reasons. First, the same code is slower the first few times it runs than after it has warmed up, so a one-shot script and a long-running server behave differently, and a micro-benchmark that does not warm up measures the wrong thing. Second, code that keeps its types and object shapes stable gives the optimizer something to rely on.
Object shape is the part most worth knowing. When you create objects with the same properties added in the same order, V8 gives them the same hidden description of their layout, called a map, and a property read can become a single offset load once the engine has seen only that one shape at a site.
function makePoint(x, y) {
return { x, y };
}
function makePointOtherOrder(x, y) {
return { y, x };
}
const first = makePoint(1, 2);
const second = makePoint(3, 4);
const third = makePointOtherOrder(5, 6);
console.log(Object.keys(first));
console.log(Object.keys(second));
console.log(Object.keys(third));[ 'x', 'y' ]
[ 'x', 'y' ]
[ 'y', 'x' ]first and second share a shape. third holds the same two properties in a different order, so it has a different shape, and a function that reads point.x and is called with all three sees two shapes at that one site. Two shapes still optimize well. Many shapes at one site, called megamorphic in V8's vocabulary, fall back to a slower generic lookup. The practical rule is small: create objects of one kind in one place, with every property present from the start, and avoid deleting properties from hot objects.
The same reasoning explains why delete has a reputation. Removing a property forces the object into a new shape, and sometimes into a slower dictionary representation. Assigning undefined or null keeps the shape and is the usual alternative when you only need the value gone. None of these effects is large in ordinary application code, and you should reach for them only after a profile points at the function, not before.
A final point about the engine: it does not run in a vacuum, and it knows nothing about timers, files or sockets. The language has no setTimeout. The host adds it, which is why the same engine in a browser and in Node.js has different globals around it, as [the post on globalThis](/library/global-object-globalthis-window-not-everywhere) shows.
The call stack
When a function is called, the engine pushes a frame onto the call stack. The frame holds the function's local variables, the arguments and the place to continue when it returns. When the function returns, its frame is popped. The function that is running is always the one on top.
function third() {
console.log("third runs");
}
function second() {
console.log("second starts");
third();
console.log("second ends");
}
function first() {
console.log("first starts");
second();
console.log("first ends");
}
first();first starts
second starts
third runs
second ends
first endsAt the moment third prints, the stack holds third, second, first and the top-level code of the file, in that order from the top. An error thrown in third that nobody catches unwinds through second and first, and the stack trace you see is exactly that list. This is why a trace reads like a path: it is the stack at the instant the error was created.
The stack has a fixed size. A function that calls itself without a stop condition keeps pushing frames until the engine refuses to allow more.
function depth(n) {
return depth(n + 1) + 1;
}
try {
depth(0);
} catch (error) {
console.log(error instanceof RangeError);
console.log(error.message);
}true
Maximum call stack size exceededThe error is a RangeError, and it can be caught like any other, but by the time it is caught the stack has already unwound to the try, so there is room again. The exact limit depends on how large each frame is and on the stack size the runtime sets, so the specification gives no number, and code that recurses to a depth of tens of thousands is a design problem rather than a configuration one. Tail calls, recursion limits and the stack size covers the ways to turn deep recursion into a loop.
Two properties of the stack explain behavior later in this guide. First, the stack is synchronous: while a frame is on it, nothing outside that call chain gets to run. Second, the event loop can run a new callback only when the stack is empty, apart from the microtask exception covered below. An empty stack is the point at which the program is idle, and the host uses that idle moment to look in its queues.
The heap and garbage collection
Objects, arrays, closures and most strings live on the heap, a large region of memory that the engine manages for you. The stack holds references to heap objects, and passing an object to a function copies the reference, not the object. That is the whole reason a function that changes a property of its argument changes it for the caller, and the reason {} === {} is false.
function rename(user) {
user.name = "Priya";
}
const account = { name: "Anil" };
rename(account);
console.log(account.name);
console.log({} === {});Priya
falseYou never free heap memory. The garbage collector frees an object when nothing reachable from a root still points at it, where the roots are the global object, the current stack, active timers and a few other host-held references. V8 divides the heap by age: most objects die young, so a quick pass over the young generation frees them cheaply, and survivors move to an old generation that is collected less often and mostly while your code keeps running. A collection needs the engine to stop your code for short moments, so the collector is another source of pauses, usually small, in the one thread you are using. How collection works, and what a leak is in a language that collects for you, is the subject of the post on garbage collection and of memory management, stack and heap.
For the event loop, one fact matters: a pending callback keeps everything it captured alive. A timer that holds a closure over a large array keeps the array until the timer fires or is cleared. A listener that is never removed keeps its whole scope for the life of the emitter. Most leaks in real programs are a queue or a registry that holds something longer than you intended.
Where asynchronous work waits
A synchronous program never needs a queue. The moment a program says "do this when the file has been read" or "do this in a second", the work has to wait somewhere, and something has to decide when it runs. That something is the host.
Take the smallest example and write down what you expect before reading the output.
console.log("first");
setTimeout(() => {
console.log("timer");
}, 0);
console.log("second");first
second
timerThe call to setTimeout runs on the stack like any other call. It asks the host to start a timer and hands over the callback. It returns at once. The host counts down on its own, and when the delay has passed it puts the callback in a queue. The callback runs only when the stack is empty, and the stack is not empty until the whole top-level script has finished, so second prints first even with a delay of zero. A zero delay means "as soon as nothing else is running", not "now".
A host keeps more than one queue, and the rules for which one is served first are what the rest of the guide is about. The two that matter in every runtime are the task queue (called the macrotask queue in older writing) and the microtask queue. Timers, I/O completions, UI events and messages from workers are tasks. Promise reactions, queueMicrotask callbacks and await continuations are microtasks.
The rule is simple to state:
Run one task from a task queue until the stack is empty.
Run every microtask, including any that the microtasks add, until the microtask queue is empty.
Do whatever else the host does between tasks (a browser may render here).
Take the next task and go back to step 1.
Every ordering puzzle in JavaScript is an application of those four steps. The top-level script itself is the first task.
Microtasks run before the next task
Run the smallest example that mixes the two kinds of work.
console.log("start");
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
queueMicrotask(() => console.log("microtask"));
console.log("end");start
end
promise
microtask
timeoutThe script is the first task. It prints start, schedules a timer, schedules two microtasks and prints end. The stack empties, so the microtask queue is drained in the order the jobs were added: the promise reaction, then the queueMicrotask callback. Only then does the loop take the next task, the timer. The timer was ready long before the script finished, and it still ran last, because microtasks always run to completion before the loop moves to another task.
That ordering has a consequence that surprises people who treat promises as another kind of callback. Promise code has priority over timers and I/O. A chain of .then calls, however long, finishes before a setTimeout(fn, 0) that was scheduled earlier.
setTimeout(() => console.log("timeout"), 0);
let count = 0;
function step() {
count += 1;
if (count <= 3) {
console.log(`microtask ${count}`);
queueMicrotask(step);
}
}
queueMicrotask(step);microtask 1
microtask 2
microtask 3
timeoutEach microtask schedules the next, and the loop keeps draining until the queue is empty. The timer waits for all three. Change count <= 3 to a condition that never ends and the timer never fires, nothing is painted in a browser and the process never reads another request. That is microtask starvation, and it is the reason a recursive queueMicrotask or a promise chain that re-enters itself belongs to the same family of bugs as an infinite loop, with the difference that the CPU is busy in the loop's own machinery and not in your function.
Promises and the order of reactions
A promise is an object with a state and a list of reactions. When it settles, each reaction becomes a microtask. Calling .then on a promise that is already settled queues the reaction at once, and calling it on a pending promise stores it until the promise settles.
const settled = Promise.resolve("ready");
settled.then((value) => console.log("A", value));
new Promise((resolve) => {
console.log("executor runs now");
resolve("done");
}).then((value) => console.log("B", value));
settled.then((value) => console.log("C", value));
console.log("sync end");executor runs now
sync end
A ready
B done
C readyThe function passed to new Promise runs immediately and synchronously, which is why executor runs now comes before sync end. Everything attached with then runs later, as microtasks, in the order the reactions were registered: A, then B, then C.
Chained then calls add one microtask per link, and two chains advance side by side.
Promise.resolve()
.then(() => console.log("a1"))
.then(() => console.log("a2"))
.then(() => console.log("a3"));
Promise.resolve()
.then(() => console.log("b1"))
.then(() => console.log("b2"));a1
b1
a2
b2
a3The first then of each chain is queued during the script, so a1 and b1 run in that order. Each of them resolves the promise that its chain's next then waits for, which queues a2 and b2, and so on. The two chains interleave one step at a time. Code that depends on one chain finishing before the other starts is depending on the count of links, which is fragile, and the fix is to express the dependency by returning or awaiting the first promise.
Returning a promise from a then handler costs extra turns. The result of the handler has to be unwrapped, which takes two additional microtasks compared with returning a plain value. Nobody should write code that depends on that count either, but it explains why puzzles that mix returned promises with plain chains produce orders that look wrong at first.
async and await in terms of the same queue
await is syntax over promises, and it does not add a new mechanism. An async function runs synchronously until its first await. At the await, the function is suspended, the awaited value is turned into a promise, and the rest of the function is scheduled as a reaction on that promise. The caller gets a promise back immediately.
async function load() {
console.log("load: before await");
await fetchData();
console.log("load: after await");
}
async function fetchData() {
console.log("fetchData runs");
return "data";
}
console.log("script start");
load();
Promise.resolve()
.then(() => console.log("promise 1"))
.then(() => console.log("promise 2"));
console.log("script end");script start
load: before await
fetchData runs
script end
load: after await
promise 1
promise 2load() runs on the stack until the await, so load: before await and fetchData runs print before script end. The fetchData() call returns an already-resolved native promise, so the continuation of load is queued as a microtask at once, ahead of promise 1, which was queued afterwards. That is the order in current engines. Older engines took three microtask turns for an await and printed the promise lines first, and the change came with the specification update that let await use a promise directly. If you read an old article with a different order for this snippet, it describes an older engine.
The practical rules are shorter than the puzzles:
Code before the first
awaitin anasyncfunction is synchronous.Code after an
awaitruns in a microtask, never in the same turn as the code that called the function.An
asyncfunction always returns a promise, and a thrown error becomes a rejection of it.
A try and catch around an await catches the rejection, because the rejection is rethrown at the await expression when the function resumes. A try around a call without await catches only errors thrown synchronously before the first await. Error handling with try, catch and finally covers where that line falls for each kind of callback.
Timers are requests, not promises
setTimeout(fn, delay) asks the host to put fn in the timer queue after at least delay milliseconds. At least, because the callback still has to wait for the stack to be empty and for any tasks ahead of it.
const start = Date.now();
setTimeout(() => {
const waited = Date.now() - start;
console.log(waited >= 100);
}, 100);
const until = Date.now() + 300;
while (Date.now() < until) {
// Hold the thread for 300 ms.
}trueThe timer asked for 100 ms and ran after roughly 300 ms, because the busy loop held the stack and the callback could not run until the script returned. The check waited >= 100 is the only claim a timer makes, and the output does not print the elapsed time because it differs on every run. A callback registered with a longer delay can never run before one registered with a shorter delay in the same queue, but two timers with the same delay run in the order they were created.
Two details about the minimum. Node.js treats a delay under 1 ms as 1 ms, so setTimeout(fn, 0) is setTimeout(fn, 1). Browsers follow the HTML specification, where timers nested more than five levels deep are clamped to at least 4 ms, so a recursive setTimeout(tick, 0) does not loop faster than about 250 times a second in a page. Neither limit is something to build on; both are reasons not to use a timer as a way to wait "one tick".
For the tick itself, use the tool that says what you want. queueMicrotask(fn) runs fn after the current work and before the next task. setTimeout(fn, 0) runs it after rendering and I/O have had a chance. In Node.js, setImmediate(fn) runs it after the current poll phase, covered next.
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function main() {
console.log("one");
await wait(50);
console.log("two");
await wait(50);
console.log("three");
}
main();
console.log("main returned");one
main returned
two
threewait is the usual way to turn a timer into something await can use. Node.js also ships setTimeout as a promise in node:timers/promises, which returns the promise directly and accepts an AbortSignal for cancellation.
The event loop in Node.js
Node.js implements the loop with libuv. Instead of one task queue, it has phases, and each phase has its own queue. The loop visits the phases in a fixed order, runs everything that is ready in each one, and goes around again until nothing is left to do, at which point the process exits.
| Phase | What runs there |
|---|---|
| timers | callbacks from setTimeout and setInterval whose time has come |
| pending callbacks | a few deferred system callbacks, such as some TCP errors |
| idle, prepare | internal use |
| poll | I/O callbacks: completed file reads, incoming sockets, most things that are not timers |
| check | setImmediate callbacks |
| close callbacks | close events, such as a socket's socket.on("close") |
Between every callback, Node.js drains two more queues: the process.nextTick queue first and the promise microtask queue second. That is the Node.js version of step 2 in the four-step rule. The timers phase is where the loop starts, and it is also where the polling phase decides how long it can wait: if there are timers, the poll phase waits for I/O no longer than the nearest timer needs, and if there are setImmediate callbacks it does not wait at all.
The ordering of setTimeout(fn, 0) and setImmediate(fn) shows the phases at work. From the main module, the order depends on how long the process took to start, because the timer is ready only if 1 ms has already passed when the loop begins. Inside an I/O callback the order is fixed, because the loop is in the poll phase and the check phase comes before the next timers phase.
import { readFile } from "node:fs";
readFile(import.meta.filename, () => {
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
});nextTick
promise
immediate
timeoutThe callback finishes, Node.js drains nextTick, then promises, which gives the first two lines. The loop moves on from the poll phase to the check phase, where setImmediate callbacks run, so immediate precedes timeout, and the timer waits for the next trip through the timers phase. Written in a file loaded as an ES module, import.meta.filename is available from Node.js 20.11, and the example reads its own file so that the callback has a real I/O completion to run from.
process.nextTick deserves a note, because its name misleads. It does not run on the next tick of the event loop. It runs when the current operation completes, before the loop continues and ahead of promise microtasks in CommonJS code. Recursive nextTick starves the loop in the same way as recursive microtasks, and the Node.js documentation recommends queueMicrotask for new code. One ordering difference between module systems is worth remembering: in a CommonJS file the nextTick queue is drained before the promise queue at the end of the main script, and in an ES module the module body itself is evaluated inside a promise job, so promise reactions run first.
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");sync
promise
nextTickSaved as order.mjs and run with node order.mjs, this prints promise before nextTick. Saved as order.cjs, the same three lines print nextTick before promise. The difference does not matter if you avoid depending on it, and a reason to prefer queueMicrotask is that it has one ordering rule everywhere.
A program stays alive while the loop has something to wait for: an active timer, an open socket, a listening server, a pending file read. Calling timer.unref() tells Node.js that this timer alone should not keep the process alive. That is how a background heartbeat avoids blocking shutdown.
const heartbeat = setInterval(() => console.log("beat"), 1000);
heartbeat.unref();
setTimeout(() => console.log("done"), 50);doneThe process prints done and exits without waiting for the interval, because the only thing left holding the loop open is an unref'd timer.
The event loop in a browser
A browser follows the same four steps with more queues and one more occupant of the loop: rendering. The HTML specification calls one pass an event loop iteration. It takes a task, runs the microtasks, and then, if it is time to draw a frame, it runs animation frame callbacks, recalculates styles and layout and paints. Painting needs the main thread, and the main thread is the one your JavaScript is using.
This turns a long task into something visible. A click handler that runs for 300 ms prevents the next frame from being produced, so the page seems frozen, text input lags and animations stutter. The Long Tasks API reports any main-thread task over 50 ms as a long task, which is a useful threshold: a handler should return quickly enough that the page can respond. The remedy is to break the work into pieces and give the loop a chance to run between them.
function wait() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
async function processInChunks(items, handle, chunkSize = 100) {
let handled = 0;
for (let index = 0; index < items.length; index += chunkSize) {
const chunk = items.slice(index, index + chunkSize);
for (const item of chunk) {
handle(item);
handled += 1;
}
await wait();
}
return handled;
}
const numbers = Array.from({ length: 1050 }, (_, index) => index);
let sum = 0;
processInChunks(numbers, (value) => {
sum += value;
}).then((count) => console.log(count, sum));1050 550725After every hundred items the function awaits a timer, so the stack empties, the browser can paint or handle input, and the loop returns to the next chunk as a new task. The total is the same as a plain loop. In a page, the better tool where it exists is scheduler.yield(), which returns control to the browser and then resumes your code ahead of other queued tasks of the same priority, and requestIdleCallback for work that can wait for idle time. Neither exists in every browser, so feature-test them and fall back to a timer.
Two other browser queues matter. requestAnimationFrame(fn) runs fn right before the next paint, which makes it the correct place for work that changes the picture, and a bad place for heavy computation. And input events are tasks, so a handler that is queued behind a long task waits for it. If a button does nothing for half a second after you click it, a task is running that should have been split, or moved to a worker.
Blocking and how to see it
Blocking means keeping the stack busy so that nothing else can run. The common causes are CPU work in the main thread and synchronous APIs.
import { readFileSync, readFile } from "node:fs";
setTimeout(() => console.log("timer fired"), 0);
console.log("reading synchronously");
const text = readFileSync(import.meta.filename, "utf8");
console.log("sync read finished", text.length > 0);
readFile(import.meta.filename, "utf8", (error, content) => {
console.log("async read finished", content.length > 0);
});
console.log("async read requested");reading synchronously
sync read finished true
async read requested
timer fired
async read finished truereadFileSync holds the thread until the file has been read, so nothing else runs during that call. For a script that runs once, that is fine and often clearer. In a server, every request that arrives while the call is in progress waits for it, so synchronous file and crypto calls belong at start-up and not in request handlers. readFile hands the work to the thread pool and returns at once, and its callback is a poll-phase task. The order of the last two lines, the timer first, depends on the file read taking longer than the timer, which is likely for a one-millisecond timer on a file system that has to schedule a thread-pool job. It is not guaranteed, and nothing should depend on it.
CPU-bound work is the harder case, because there is no asynchronous version of a loop. Sorting a large array, parsing a very large JSON document, hashing in pure JavaScript or computing a result for each of a million records occupies the thread. When the loop must stay responsive, there are three options: split the work into chunks as above, move the work to a worker, or move it out of the process.
To see whether the loop is healthy, Node.js reports the delay between when a timer should have fired and when it did, through perf_hooks.
import { monitorEventLoopDelay } from "node:perf_hooks";
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
const until = Date.now() + 200;
while (Date.now() < until) {
// Block the loop for 200 ms.
}
setTimeout(() => {
histogram.disable();
const maxMs = histogram.max / 1e6;
console.log("loop was delayed:", maxMs > 100);
}, 50);loop was delayed: trueThe histogram records in nanoseconds, so the code divides by a million to compare against milliseconds. The example prints a boolean because the real maximum differs on every machine. A production service exports the histogram's percentiles to its metrics system, and a rising p99 means that something is holding the loop. performance.eventLoopUtilization() gives the share of time the loop was busy, which is the number to watch when deciding whether a process is CPU-limited. For finding the function responsible, node --cpu-prof writes a profile that Chrome DevTools opens, and the long bar at the top of the flame chart is the task that blocked.
Moving work to another thread
A worker has its own stack, its own heap and its own event loop, and it communicates through messages that are copied with the structured clone algorithm. Nothing is shared by default, which keeps the run-to-completion rule intact: a variable in one realm can be written only by that realm's code.
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url), {
workerData: { n: 35 },
});
worker.on("message", (value) => console.log("fib(35) =", value));
worker.on("error", (error) => console.log("worker failed:", error.message));
console.log("main thread stays free");
} else {
parentPort.postMessage(fib(workerData.n));
}main thread stays free
fib(35) = 9227465The main thread starts the worker, registers the listeners and prints immediately. The worker loads the same file, sees that isMainThread is false, computes the result and posts it back, where it arrives as a task on the main thread's event loop. The calculation took the worker's thread and never touched the main one, so a timer on the main thread would have fired on time throughout.
Workers cost memory and start-up time, since each one loads its own copy of the engine's state, so you create a few and reuse them as a pool, and you send results back rather than creating a worker per task. Data that is large can move without a copy: an ArrayBuffer can be transferred, which moves ownership, and a SharedArrayBuffer can be shared with Atomics for coordination. Typed arrays and ArrayBuffer shows what those buffers are. Objects from a worker are separate in another way too: each worker is its own realm, so instanceof Array can disagree across the boundary, a point covered in what a realm is.
In a browser the equivalent is new Worker("worker.js") with postMessage and onmessage, with no access to the DOM from the worker. The rule to keep is the same in both: work that does not touch shared UI or request state and takes more than a few milliseconds is a worker candidate.
Unhandled rejections and the loop
A rejected promise with no handler is a bug that the host reports. In Node.js, the check happens after the microtask queue has drained, so a handler attached in the same turn is fine, and one attached later is not.
process.on("unhandledRejection", (reason) => {
console.log("unhandledRejection:", reason.message);
});
process.on("rejectionHandled", () => {
console.log("rejectionHandled");
});
const failure = Promise.reject(new Error("boom"));
setTimeout(() => {
failure.catch(() => console.log("caught late"));
}, 10);unhandledRejection: boom
caught late
rejectionHandledThe rejection happens during the first turn and has no handler when the microtask queue empties, so Node.js emits unhandledRejection. Because the process has a listener, it carries on and does not throw. The timer then attaches a handler 10 ms later: the handler runs, and rejectionHandled follows. Without the unhandledRejection listener, Node.js 15 and later raise the error as an uncaught exception and exit with a non-zero code, which is the behavior you want in a server, since a rejection nobody handles is a state the program did not plan for.
The lesson for the loop is about timing. A handler must be attached before the current stack and its microtasks finish, which in practice means attaching it where the promise is created or returned. Code that stores a promise and attaches catch after a timer or an await of something else invites this report. When you start several promises and await them one at a time, a later one that rejects while you are still awaiting an earlier one has no handler yet, which is one more reason to collect them with Promise.all or Promise.allSettled.
Putting the rules together
A longer example uses all of it: synchronous code, timers, promises, async functions and an I/O callback. Work out the order yourself before reading the output, by applying the four steps.
import { readFile } from "node:fs";
console.log("1 script");
setTimeout(() => console.log("2 timeout"), 0);
setImmediate(() => console.log("3 immediate"));
readFile(import.meta.filename, () => console.log("4 file read"));
Promise.resolve().then(() => console.log("5 promise"));
(async () => {
console.log("6 async start");
await null;
console.log("7 async resume");
})();
queueMicrotask(() => console.log("8 microtask"));
process.nextTick(() => console.log("9 nextTick"));
console.log("10 script end");1 script
6 async start
10 script end
5 promise
7 async resume
8 microtask
9 nextTick
2 timeout
3 immediate
4 file readThe first, sixth and tenth lines are the script: the async function runs synchronously up to its await. When the script ends, the host drains the microtask queue, and in an ES module the promise queue runs before nextTick, so the three promise jobs print in the order they were queued, 5, 7, 8, followed by the nextTick callback, 9. The loop then enters its phases. The timer is ready if 1 ms has passed, which for a script that has read and compiled a module it usually has, so 2 timeout is the output here, although a faster machine could print 3 immediate first. The file read needs a pass through the thread pool, so it finishes in a later poll phase.
The lines that are guaranteed are the ones set by the language and by the drain rule: 1, 6, 10, then 5, 7, 8. The relative order of 2, 3 and 4 is not guaranteed from the main module. That uncertainty is the reason tests that compare the order of a timer against setImmediate from top-level code are flaky, and the reason to use an I/O callback or a promise to enforce an order you need.
Common beliefs that are wrong
A few statements about the loop get repeated until they are accepted, and each of these is wrong in a way that costs time.
"Promises make code run in parallel." A promise models a value that is not ready yet. The code that produces it may run in the thread pool or the operating system, which is parallel, or in your own thread, which is not. new Promise((resolve) => resolve(heavyLoop())) runs heavyLoop synchronously on the caller's stack.
**"async functions run on another thread."** An async function is an ordinary function on the ordinary stack that can suspend at an await. The part after the await runs on the same thread later.
**"setTimeout(fn, 0) runs immediately."** It runs after the current stack, after every microtask, and after any task that was queued first. In Node.js it is a 1 ms timer.
"The event loop checks the queue while my code runs." It cannot. The loop is not a separate thread that peeks at the stack. It is the code that runs when the stack is empty.
"Awaiting in a loop is always a mistake." Awaiting one item at a time is sequential, which is wrong when the items are independent and right when each step depends on the last, or when you want to limit pressure on a service. Choosing between a sequential loop and Promise.all is a design decision, not a defect. [The comparison of for...of and forEach](/library/vs-vs-foreach) shows why forEach is the wrong tool for it.
"Callbacks are slower than promises, or the reverse." Neither is meaningfully slower in the way people mean. The cost that matters is a task that holds the stack, not the choice between two ways of resuming.
Testing code that depends on ordering
Tests of asynchronous code fail for the same reasons production does: an assumed order that nothing enforces. Two habits keep them stable. First, assert on what the code guarantees, such as that a handler runs after the awaited value resolves, and not on how many turns it took. Second, control time instead of waiting for it.
Node.js ships a test runner with mock timers, so a test that depends on a 60-second timeout need not wait 60 seconds.
import { test } from "node:test";
import assert from "node:assert/strict";
function remindLater(send, delayMs) {
setTimeout(() => send("reminder"), delayMs);
}
test("sends the reminder only after the delay", (context) => {
context.mock.timers.enable({ apis: ["setTimeout"] });
const sent = [];
remindLater((message) => sent.push(message), 60_000);
context.mock.timers.tick(59_999);
assert.deepEqual(sent, []);
context.mock.timers.tick(1);
assert.deepEqual(sent, ["reminder"]);
});In a terminal, the default reporter prints this:
✔ sends the reminder only after the delay (1.2ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 52.4context.mock.timers replaces setTimeout for the test and advances a fake clock when you call tick, so the test runs in microseconds and checks both sides of the boundary. The durations in the report differ from run to run. The mock covers timers but not promise ordering, which stays real, so an await in the code under test still waits for the microtask queue. When a test needs the microtasks to finish, await a resolved promise in the test or use setImmediate to let everything queued so far run, and avoid the fixed sleeps that make suites slow and flaky.
For code with real I/O, wait on the event that signals completion instead of a duration. events.once(emitter, "close") returns a promise that resolves when the event fires, and it rejects if the emitter emits error first, which is the behavior most tests want.
A worked example: a job runner that keeps the loop free
A last example builds something realistic from the pieces: a function that processes a long list of jobs without blocking, reports progress and can be cancelled. The design uses chunking with setImmediate, an AbortSignal and a promise, so every rule above appears in it.
import { setImmediate as yieldToLoop } from "node:timers/promises";
export async function runJobs(jobs, { signal, chunkSize = 50 } = {}) {
const results = [];
for (let index = 0; index < jobs.length; index += chunkSize) {
signal?.throwIfAborted();
for (const job of jobs.slice(index, index + chunkSize)) {
results.push(job());
}
await yieldToLoop(undefined, { signal });
}
return results;
}
const jobs = Array.from({ length: 120 }, (_, number) => () => number * 2);
const controller = new AbortController();
setImmediate(() => console.log("other work ran between chunks"));
runJobs(jobs, { signal: controller.signal }).then((results) => {
console.log(results.length, results[119]);
});other work ran between chunks
120 238runJobs handles fifty jobs synchronously, then awaits setImmediate from node:timers/promises, which returns control to the loop and resumes in the check phase. The unrelated setImmediate callback was queued first, so it runs in that gap and prints while the work is still in progress, and the second line prints when the third chunk finishes. The signal is checked before each chunk, and the promise from setImmediate also rejects with an AbortError if the signal fires while waiting, so cancellation takes effect at the next chunk boundary and not at the end.
Three decisions are visible in it. The chunk size trades responsiveness for overhead, because a smaller chunk yields more often and pays the cost of a trip through the loop each time, and the right size is the one that keeps each chunk well under the delay you can tolerate on the loop. The yield uses setImmediate and not queueMicrotask, because a microtask would not let the timer or any I/O run. And the function returns a promise, so the caller decides whether to await it, which keeps the loop discipline inside the function and out of every call site.
If the jobs themselves are heavy, chunking helps responsiveness and does nothing for throughput, since the work still uses one thread. At that point the same runJobs shape moves into a worker, and the main thread keeps only the message handling.
When this model stops
The model above is the one every JavaScript runtime shares, and it leaves out several things you will meet. The details of phases belong to Node.js, and Deno and Bun implement their own loops with the same microtask rules but different internals for I/O, so a claim about setImmediate or process.nextTick is a Node.js claim, and the other runtimes only emulate those APIs for compatibility. Browsers add rendering steps, task priorities and per-source queues that the specification allows to be ordered differently, so only the ordering inside one queue is guaranteed. Workers and Atomics.wait allow a worker to block on purpose, which the main thread of a browser must never do.
It also leaves out the real cost of the engine's choices. Pause times from garbage collection, the warm-up of the optimizer and the memory a closure retains are real and show up as latency, and they come from the mechanisms in the first sections, not from the loop. When a profile shows time spent in the collector or in a deoptimized function, no change of queue discipline will help, and the fix is in the allocation pattern or the shape of the data.
The last limit is the one that applies to nearly every project: a runtime model predicts order, and it does not tell you what your program should do. Whether to await in a loop, how large a chunk to take, whether to bound concurrency and what to do when a task fails are design choices that the rules inform and do not decide. Start from the simplest correct sequence, measure the loop's delay under realistic load and change the structure only where the numbers show a task holding the thread.


