Why can identical JavaScript print different results in different runtimes? Scheduling determines when a host makes deferred code eligible to run. Registering a callback does not run it: a browser button’s onclick handler, for example, runs only after a click. The event loop reacts to events and runs their associated work. Code already running completes before the loop moves to another task. section 1.3.1 section 8.4.4
A callback crosses a stack boundary
In a forEach loop, callbacks run inside the caller’s current stack: logging each item precedes logging 'done'. Wrap each item’s log in setTimeout, and 'done' appears first. The loop schedules callbacks but finishes before they run. Each deferred callback starts on a new stack, retaining access to closed-over variables but not the caller’s active try/catch. section 8.2
Execution order depends on queues, when a runtime drains them, and the context in which work is scheduled—not on a universal priority assigned to each API. queueMicrotask and Promise.then schedule microtasks; process.nextTick, setTimeout, and setImmediate use other runtime-dependent mechanisms. Browsers instead offer rendering-related scheduling through requestAnimationFrame and requestIdleCallback. The language specification does not prescribe one operating-system-thread model, and hosts differ in their event-loop implementations. section 1.3.1 section 8.4.4
The same file, a different order
In Node.js, a small program whose microtask and nextTick callbacks enqueue more of each can print B, A, A, B when run as a CommonJS .js file, but A, B, B, A as an ECMAScript .mjs file. CommonJS starts the program as a task and drains nextTick callbacks before microtasks. Module execution begins in a microtask context, changing which queued work gets its turn first. Predict order from the execution context and queue-draining points, not merely the order of scheduling calls. section 8.5.3
queueMicrotask(() => {
queueMicrotask(() => console.log('A'));
process.nextTick(() => console.log('B'));
});
process.nextTick(() => {
queueMicrotask(() => console.log('A'));
process.nextTick(() => console.log('B'));
});
Run this listing first as .js, then as .mjs in Node.js to inspect how nested microtask and nextTick scheduling changes the output. section 8.5.3
When ordering matters, identify the host, the current execution context, and the queue used by each API. Do not assume that Node.js compatibility APIs in Deno or Bun reproduce Node.js ordering, or that an API available in one host exists in a browser. section 8.4.4 section 8.5.3





