0 ms1console.log("start");2setTimeout(() => {3 console.log("timeout");4}, 0);5Promise.resolve().then(() => {6 console.log("promise");7});8console.log("end");Consolestartorder.js:1endorder.js:8promiseorder.js:6timeoutorder.js:3scriptcallbackconsole.logstartendpromisetimeout
Back: the call stack, the event loop, the two queues and the host's timerFront: the script order.js and the developer consoleMovers: frames on the stack, the two callbacks, and the printed wordsAt the back, the call stack, the event loop, the microtask queue, the task queue and the host's timer. In front, the script order.js and the developer console. The script runs to the end first, printing start and end; its two callbacks wait in the queues. Once the stack is empty, the loop runs every microtask, then one task: promise, then timeout. Task queue is the HTML Standard's name (people also say macrotask). The ECMAScript spec calls promise callbacks Jobs and asks the host to queue them; browsers and Node.js run them as microtasks. Node.js has its own loop phases but prints the same order here.

One thing at a time

  1. JavaScript runs your code on one thread, with one call stack: a pile of the functions running right now. It does one thing at a time. Waiting is left to the host, the browser or Node.js.

Running the script

The event loop

What happens

// step 1/10 · one-thread
thread      one: JavaScript does one thing at a time
call stack  one frame per running function call
            the newest frame on top, last in, first out
host        the browser or Node.js: timers, queues,
            and the event loop that feeds the stack

A delay of 0 ms is the shortest wait, not a promise of speed. Browsers make deeply nested timers wait at least 4 ms, and Node.js turns a delay below 1 into 1 ms. Either way the callback waits for an empty stack and for every microtask. The figure shows the timer queuing its callback while the script still runs. The exact moment depends on the host; the printed order does not, because nothing leaves a queue until the script has finished.