The event loop: the stack, tasks and microtasks

A JavaScript program runs on one thread, and everything that has to wait goes on a queue. The event loop takes one task from that queue when the stack is empty, runs it to its end, and then empties a second, shorter queue of microtasks before it takes another task. That single rule explains the order of the log lines in every example of this part.

The lesson follows four short programs: the order of a synchronous line, a timer and a promise; a function that returns while its callback is still to come; a microtask that queues two more; and a loop that holds the thread so long that a timer has to wait for it. No block prints a duration, only the order.

The order of the logs

The program below writes two lines straight away, queues a timer for later and queues a promise. The two synchronous lines print first because they are on the stack, then the microtasks of the promise queue, and the timer last, because a task runs only when the stack is empty and the microtasks are gone.

The file order.mjs:

console.log('sync: first'); setTimeout(() => { console.log('timer: last'); }, 10); Promise.resolve().then(() => { console.log('microtask: promise'); }); queueMicrotask(() => { console.log('microtask: queueMicrotask'); }); console.log('sync: second');

node order.mjs

sync: first
sync: second
microtask: promise
microtask: queueMicrotask
timer: last

The two microtasks kept the order they were queued in, and both ran before the timer even though the timer was registered first. A microtask is not a task: the loop empties that queue completely between two tasks, which is why a promise callback never waits for a timer with a delay of zero.

The call stack runs to the end

A function that registers a timer returns at once, and the callback runs after the whole stack of the program is gone. The frame of the timer is not on the stack when the callback runs: the loop calls it as a new task, and it starts a stack of its own.

The file stack.mjs:

function inner() { console.log('inner: start'); setTimeout(() => { console.log('inner: the timer callback'); }, 10); console.log('inner: end'); } console.log('before'); inner(); console.log('after');

node stack.mjs

before
inner: start
inner: end
after
inner: the timer callback

The callback came after after, though the timer was set before inner returned. That is the rule that makes a callback safe for a long operation: it never runs in the middle of the frame that scheduled it, so the state that frame was building is finished by the time the callback sees it.

Microtasks drain first

A microtask that queues another microtask does not wait for the next turn of the loop: the new one joins the same queue and runs before any task. The program below queues four of them from two places, and the order shows how the queue grows while it is being emptied.

The file micro.mjs:

setTimeout(() => { console.log('timer'); }, 10); Promise.resolve().then(() => { console.log('microtask one'); Promise.resolve().then(() => { console.log('microtask three'); }); queueMicrotask(() => { console.log('microtask four'); }); }); queueMicrotask(() => { console.log('microtask two'); });

node micro.mjs

microtask one
microtask two
microtask three
microtask four
timer

Two ran, then the two that were added while the queue was being emptied, and only then the timer. A chain of promises therefore runs to its end before the next task, and a promise that keeps resolving another promise can keep a timer waiting for a long time, which is the reason a long microtask chain is a bug and not a detail.

One thread

The loop cannot take a task while a frame is running, so a long loop delays everything else. The program sets a timer for ten milliseconds and then holds the thread for longer than that: the callback cannot run before the loop is done, however late the timer is.

The file block.mjs:

setTimeout(() => { console.log('the timer callback waits for the loop'); }, 10); console.log('the loop starts'); const start = Date.now(); while (Date.now() - start < 50) { // the thread is busy, so nothing else can run } console.log('the loop is done');

node block.mjs

the loop starts
the loop is done
the timer callback waits for the loop

The callback printed last, and the block prints no duration because the exact delay is the business of the machine. What the order shows is enough: a computation that takes a moment is a delay for every timer, every socket and every request in the process, which is why a server moves a heavy job off the loop rather than into it.

Exercises

  1. Add a second timer with a delay of 20 milliseconds to the first program. Where does its line appear, and why?
  2. Move the console.log('sync: second') line above the setTimeout call. Does the order change?
  3. Queue three microtasks from inside a microtask and print each. Which one is last before the timer?
  4. Replace the promise in the first program with Promise.resolve().then(() => Promise.resolve()).then(...) and count the lines before the timer.
  5. Put a loop of a second into the timer callback of the third program. Which line of the program is printed after the loop?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the call stack?

    Answer

    The frames of the functions that are running

    The stack holds the frames of the current call, and a frame leaves when its function returns.

  2. When does a timer callback run?

    Answer

    When the stack is empty and the microtasks are done

    The timer makes a task, and a task waits for the stack and for the microtask queue.

  3. What is a microtask?

    Answer

    A callback queued by a promise or by queueMicrotask

    Promises and queueMicrotask fill the microtask queue, which is emptied between two tasks.

  4. Which runs first: setTimeout with a delay of 0 or a promise callback queued before it?

    Answer

    The promise callback

    The microtask queue is emptied before the loop takes the next task, whatever its delay.

  5. What does this program print? console.log("a"); setTimeout(() => console.log("b"), 0); Promise.resolve().then(() => console.log("c")); console.log("d");

    Answer

    a / d / c / b

    The two synchronous lines run first, the microtask next, and the timer as the next task.

  6. What does this program print? queueMicrotask(() => console.log("one")); Promise.resolve().then(() => console.log("two"));

    Answer

    one / two

    Both are microtasks on one queue, and they run in the order they were queued.

  7. What does this program print? setTimeout(() => { console.log("timer"); Promise.resolve().then(() => console.log("inside the timer")); }, 0); Promise.resolve().then(() => console.log("outside"));

    Answer

    outside / timer / inside the timer

    The microtask outside runs first, and the one queued inside the timer runs when that task ends.

  8. Why does a long loop delay a timer that was set before it?

    Answer

    The loop keeps the only thread busy, so no task can start

    One thread runs either the loop or a callback, and the loop was there first.

  9. What does the event loop do between two tasks?

    Answer

    It empties the microtask queue

    The microtask queue is drained completely before the next task is taken.

  10. What does this program print? async function f() { console.log("one"); await null; console.log("three"); } f(); console.log("two");

    Answer

    one / two / three

    The await pauses the function and lets the caller print, and the rest runs as a microtask.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image