SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 23
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 23 of 30

Event loop output questions

setTimeout vs promises vs async/await vs queueMicrotask vs process.nextTickpredicting the order6 puzzles

These are the notes for JavaScript Coding Questions, episode 23, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode we wrote our own Promise.all and a worker pool. Today is the most famous interview round of all: "what does this code print?" We mix setTimeout, promises, async/await, queueMicrotask and process.nextTick in six puzzles, grouped as three interview questions. On the way: why setTimeout(fn, 0) is not "now", why a promise jumps ahead of a timer, why an async function is not "later", and a microtask that never lets a timer run.

Each puzzle follows the same steps: the code, the obvious guess, the real output, why the guess was wrong, and the rule that fixes our mental model. The next puzzle tests that rule. At the end there is a 3-step method that solves any output question.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. A file with no import, export or top-level await (an await outside any function) is run by Node as a CommonJS file, Node's older module format. That matters for one puzzle: in an ES module (the standard import/export format), the order of process.nextTick and then flips. Both outputs are shown in "Going further".

First: one thread, the call stack, run to completion

  • JavaScript runs your code on one thread: one line of work, so it does one thing at a time.
  • The call stack is the list of functions running right now. Calling a function puts it on top; returning takes it off. The one on top is the one running.
  • Run to completion: a piece of code is never stopped halfway to run something else. Once a function starts, it runs until it returns.
  • A callback is a function you hand over to be called later (by a timer, a promise, a file read).
function makeChai() {
  console.log("  makeChai starts");
  addSugar();
  console.log("  makeChai ends");
}
function addSugar() {
  console.log("    addSugar runs");
}
console.log("start");
makeChai();
console.log("end");
start
  makeChai starts
    addSugar runs
  makeChai ends
end

makeChai is on the stack, addSugar goes on top of it, runs, comes off, and makeChai continues. Plain function calls are synchronous: they finish before the next line runs. So who runs a callback, and when? That's the job of the event loop: the loop that, whenever the call stack is empty, picks the next waiting callback and runs it. Let's discover its rules, one puzzle at a time.

Q1: Timers vs promises

Puzzle 1: the chai stall (setTimeout 0)

A chai stall. Take the order, start a timer of 0 milliseconds that says the chai is ready, then give the customer a token.

console.log("1. take the order");
setTimeout(() => console.log("2. chai is ready"), 0);
console.log("3. give the token");

The obvious guess: zero milliseconds sounds like "right now", so 1, 2, 3.

The real output:

1. take the order
3. give the token
2. chai is ready

Why. setTimeout doesn't run the function. It hands it to a timer and returns at once. When the time is up, the callback joins a waiting line called the task queue. A task (also called a macrotask) is one callback the event loop runs from that line. The event loop only takes from the task queue when the call stack is empty, when all the current code has finished. So 2 must wait for line 3.

Rule 1: setTimeout(fn, 0) means "as soon as the stack is empty", not "now".

Real life: one chaiwala serves one customer at a time, start to finish (the call stack). Ready chai doesn't jump into his hands; it gets a token and waits in line (the task queue). Only when he has finished the current customer does he call the next token, never in the middle (the event loop).

The 0 is also only a minimum. If the current code is slow, the timer waits for it:

const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
setTimeout(() => console.log("timer ran at", ms()), 0);
const start = Date.now();
while (Date.now() - start < 500) {}
console.log("loop done at", ms());
loop done at 500
timer ran at 500

(Times are rounded to 100 ms so the output is stable.) The 0 ms timer ran at 500 ms, because the while loop held the only thread for half a second.

Puzzle 2: a promise and a timer

Log A. A 0 ms timer that logs B. A promise that is already resolved, with a then that logs C. Log D.

console.log("A");
setTimeout(() => console.log("B timeout"), 0);
Promise.resolve().then(() => console.log("C then"));
console.log("D");

The guess from rule 1: A and D first, because the stack must be empty. Then B, because the timer was scheduled before the then. So A, D, B, C?

The real output:

A
D
C then
B timeout

Why. Promise callbacks don't go to the task queue. They go to a second line, the microtask queue. A microtask is a small job that must run as soon as the current code finishes, before anything else. The event loop's rule: after each task, empty the whole microtask queue, then take the next task. The whole script is itself the first task, so C (a microtask) runs before B (the next task).

Rule 2: run one task, then every microtask, then the next task, and so on.

  • Microtasks come from: then / catch / finally callbacks, the rest of an async function after await, and queueMicrotask(fn).
  • Tasks come from: setTimeout, setInterval, setImmediate, I/O callbacks (a file read, a network reply), and in browsers, clicks and other events.

Real life: the chaiwala is serving a customer (one task). Before he's done, the customer says "just one more thing, add sugar". He finishes that before calling anyone new (a microtask). Only then does he call the next token (the next task).

Q2: async and await

Puzzle 3: an async function

placeOrder logs 2, awaits null, then logs 4. Outside, we log 1, call placeOrder, and log 3.

async function placeOrder() {
  console.log("2 order placed");
  await null;
  console.log("4 payment checked");
}
console.log("1 start");
placeOrder();
console.log("3 next customer");

The obvious guess: "async" sounds like "later", so 1, 3, then 2, 4.

The real output:

1 start
2 order placed
3 next customer
4 payment checked

Why. Calling an async function runs its body straight away, on the same call stack, like any function. It only pauses at the first await. The rest of the function, after the await, becomes a microtask. So 2 prints at once, the function returns a promise to the caller, 3 prints, and 4 runs after the current code is done. (await null waits even though null isn't a promise: it still lets the current code finish first.)

Rule 3: an async function is synchronous until its first await. Only the part after the await waits.

Puzzle 4: a then chain and queueMicrotask

A timer. A chain of two thens. queueMicrotask(fn), which puts fn straight into the microtask queue. And log sync.

setTimeout(() => console.log("timeout"), 0);
Promise.resolve()
  .then(() => console.log("then 1"))
  .then(() => console.log("then 2"));
queueMicrotask(() => console.log("microtask"));
console.log("sync");

The guess: sync first and timeout last (we know that now). The chain was written first, so then 1, then 2, microtask?

The real output:

sync
then 1
microtask
then 2
timeout

Why. A then only queues its callback when the promise before it settles (becomes fulfilled or rejected). Promise.resolve() is already fulfilled, so then 1 is queued at once. But .then(...) returns a new promise, which is only fulfilled when then 1 has run. So then 2 isn't queued until then. By that time, the queueMicrotask callback was already waiting in line, so it goes first.

Moment Microtask queue
end of sync code then 1, microtask
then 1 runs, its promise is fulfilled microtask, then 2
microtask runs then 2
then 2 runs (empty) → now the task timeout

Rule 4: a then chain doesn't stay together. Each then is one step in line, queued only when the previous one settles.

Q3: Node's extra queue

Puzzle 5: process.nextTick

process.nextTick(fn) exists only in Node, not in browsers. It means "run fn right after the current code". A then, a nextTick, a timer, and log sync:

Promise.resolve().then(() => console.log("then"));
process.nextTick(() => console.log("nextTick"));
setTimeout(() => console.log("timeout"), 0);
console.log("sync");

The guess: the then was queued before the nextTick. First in, first out (FIFO: whatever joins a line first leaves it first), so sync, then, nextTick, timeout?

The real output:

sync
nextTick
then
timeout

Why. Node keeps a separate nextTick queue, and empties it before the promise microtask queue. Both run before any timer. FIFO is true inside each line, not across lines.

Warning: this file is CommonJS. In an ES module, the order of these two flips (see "Going further").

Real life: the stall now has three lines. First, the owner's own requests, always served first (nextTick). Second, the "just one more thing" requests (then, await, queueMicrotask). Third, the next token, only when both other lines are empty (setTimeout).

A real bug: starving a timer

A 0 ms timer, and a microtask that queues itself again, 100,000 times. Picture a progress check that keeps re-scheduling itself. When does the timer run?

let n = 0;
setTimeout(() => console.log("timeout finally ran after", n, "microtasks"), 0);
function again() {
  if (++n < 100000) queueMicrotask(again);
}
queueMicrotask(again);
console.log("sync done");
sync done
timeout finally ran after 100000 microtasks

Why. The event loop empties the microtask queue completely before the next task, including microtasks added while emptying it. A microtask that keeps adding microtasks never lets a timer, a network reply or a click get a turn. This is called starvation: one kind of work never gets to run because another keeps cutting in. Here it stopped at 100,000; with no limit, the timer would never run and the program would hang. The same happens with a process.nextTick that keeps calling process.nextTick.

Rule 5: if work must repeat, schedule it with setTimeout (or setImmediate), so other tasks get a turn in between. (Practice question 5 shows the fix.)

Puzzle 6: the boss

The 3-step method for any output question

  1. Run all the sync code, top to bottom, including async functions up to their first await and the function passed to new Promise. Note every callback that gets queued, and which line it joins.
  2. Empty the nextTick queue, then the microtask queue. New ones join the end of their line, and still run in this step.
  3. Take ONE task (the oldest timer that is due), run it, then go back to step 2.

Pause and write all nine numbers before you look at the output.

console.log(1);
setTimeout(() => {
  console.log(2);
  Promise.resolve().then(() => console.log(3));
}, 0);
(async () => {
  console.log(4);
  await Promise.resolve();
  console.log(5);
  setTimeout(() => console.log(6), 0);
})();
process.nextTick(() => console.log(7));
queueMicrotask(() => console.log(8));
console.log(9);
1
4
9
7
5
8
2
3
6

Step-by-step trace

(async () => { ... })() is an async arrow function called at once (an IIFE: immediately invoked function expression). "rest-of-async" means the part after its await.

Step What runs Output Queues after (nextTick · microtask · task)
1 console.log(1) 1 · ·
2 setTimeout(timer A) (logs 2, queues 3) · · timer A
3 async arrow starts: console.log(4), then await pauses it 4 · rest-of-async · timer A
4 process.nextTick(7) 7 · rest-of-async · timer A
5 queueMicrotask(8) 7 · rest-of-async, 8 · timer A
6 console.log(9); sync code done 9 7 · rest-of-async, 8 · timer A
7 nextTick queue: 7 7 · rest-of-async, 8 · timer A
8 microtask: rest-of-async logs 5 and starts timer B (logs 6) 5 · 8 · timer A, timer B
9 microtask: 8 8 · · timer A, timer B
10 task: timer A logs 2 and queues then(3) 2 · 3 · timer B
11 step 2 again, microtask: 3 3 · · timer B
12 task: timer B 6 · ·
  • 4 is sync, because an async function runs until its first await.
  • 7 before 5 and 8: the nextTick queue goes first (in CommonJS).
  • 3 before 6, even though the then for 3 is created later than the timer for 6. Timer B (for 6) only started when 5 ran (step 8), after timer A was already waiting, so it is second in the task line. And 3 is a microtask queued by timer A, so it runs right after timer A, before the next task.

Going further

(a) The same puzzle 5 as an ES module: the order flips

Exactly the same four lines as puzzle 5, saved as main.mjs (the .mjs extension tells Node "this is an ES module"):

Promise.resolve().then(() => console.log("then"));
process.nextTick(() => console.log("nextTick"));
setTimeout(() => console.log("timeout"), 0);
console.log("sync");
sync
then
nextTick
timeout

Compare with the CommonJS run (main.js): sync, nextTick, then, timeout. Same code, then and nextTick swapped.

A main.js that uses top-level await is also run as an ES module, so it flips too:

await null;
Promise.resolve().then(() => console.log("then"));
process.nextTick(() => console.log("nextTick"));
setTimeout(() => console.log("timeout"), 0);
console.log("sync");
sync
then
nextTick
timeout

Why. An ES module's code is itself run from inside the promise machinery (module loading is asynchronous). When the module's code finishes, the engine is already in the middle of emptying the microtask queue, so then runs right away. Node only gets to its nextTick queue after that. In CommonJS, the file runs as plain sync code, and Node empties the nextTick queue first. In an interview, say which format you assume: "in a CommonJS file, nextTick comes first".

(b) setImmediate vs setTimeout(fn, 0)

setImmediate(fn) is Node only. It runs fn in the check phase of Node's event loop. Node's loop goes round in phases (stages, always in the same order): timers (due setTimeout/setInterval callbacks), then poll (waiting for and running I/O callbacks, like a finished file read), then check (setImmediate callbacks), and round again.

In the main module:

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));

We ran this 100 times in a loop. What we saw: immediate first 94 times, timeout first 6 times. A typical run:

immediate
timeout

So it is not deterministic: the order depends on timing. setTimeout(fn, 0) is really 1 ms in Node. When the loop starts, if that 1 ms has already passed, the timers phase runs timeout first; if not, the loop moves on to check and runs immediate first. On a fast, idle machine, "not yet" usually wins; on a busy one, it can go the other way. If the main code is slow, the timer is surely due when the loop starts:

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
const start = Date.now();
while (Date.now() - start < 5) {}
timeout
immediate

We ran this one 20 times: timeout first all 20 times.

Inside an I/O callback, it is deterministic. fs.readFile(path, callback) reads a file and calls callback from the poll phase. __filename is the path of the current file (CommonJS):

const fs = require("fs");
fs.readFile(__filename, () => {
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
});
immediate
timeout

We ran it 100 times: immediate first all 100 times. After the poll phase, the next phase is always check, so the immediate runs before the loop comes back round to timers.

(c) Browser vs Node

  • Same in both: one thread, the call stack, the task queue, the microtask queue, then/await/queueMicrotask as microtasks, setTimeout as a task, rule 2 (all microtasks after each task).
  • Node only: process.nextTick and its queue, setImmediate, the named phases (timers, poll, check).
  • Browser only: rendering (painting the screen) happens between tasks, plus requestAnimationFrame. So in a browser, endless microtasks also freeze the page: no clicks, no painting.
  • Browsers clamp nested timers: after a few levels of setTimeout inside setTimeout, the minimum delay becomes about 4 ms.

There is no browser in our compiler, but we can imitate a browser's globals with Node's vm module (it runs code in a fresh, empty global object). We give it only console, setTimeout and queueMicrotask:

const vm = require("vm");
const browserLike = vm.createContext({ console, setTimeout, queueMicrotask });
vm.runInContext(`
  console.log("process:", typeof process);
  console.log("setImmediate:", typeof setImmediate);
  setTimeout(() => console.log("timeout"), 0);
  Promise.resolve().then(() => console.log("then"));
  queueMicrotask(() => console.log("microtask"));
  console.log("sync");
`, browserLike);
process: undefined
setImmediate: undefined
sync
then
microtask
timeout

This is a simulation in Node, not a real browser, but the rule is the same: with no nextTick, code that must run "right after the current code" in both places uses queueMicrotask. In a real browser, process.nextTick(...) would throw ReferenceError: process is not defined.

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
setTimeout(fn, 0) runs now puzzle 1 1, 3, 2 it waits for an empty stack 0 ms = after the current code
Timers before promises puzzle 2 A, D, C then, B timeout microtasks run before the next task then beats setTimeout
async = runs later puzzle 3 1, 2, 3, 4 sync until the first await only the part after await waits
A then chain stays together puzzle 4 then 1, microtask, then 2 each then is queued when the previous settles count one step per then
FIFO across queues puzzle 5 sync, nextTick, then, timeout nextTick queue is emptied first three lines, each FIFO inside
Same order in ES modules puzzle 5 as .mjs sync, then, nextTick, timeout module code runs inside the promise machinery say "CommonJS" or "ES module"
Microtasks that re-queue forever starvation program timeout finally ran after 100000 microtasks the queue is emptied completely use setTimeout for repeated work
The new Promise function is async below executor body before sync the executor runs synchronously only then callbacks wait
setImmediate always first (b) above 94 immediate-first, 6 timeout-first depends on timing in the main module only inside I/O is it fixed
await null lets timers run mini project doorbell answered at 600 await gives a microtask, not a task yield with setImmediate/setTimeout

The executor row, for real. The executor is the function you pass to new Promise:

const p = new Promise((resolve) => {
  setTimeout(() => {
    console.log("executor timer");
    resolve("done");
  }, 0);
  console.log("executor body");
});
p.then((v) => console.log("then got", v));
console.log("sync");
executor body
sync
executor timer
then got done

The executor's body runs at once. The then callback is only queued when resolve is called, inside the timer.

Mini project 1: a logger that batches with queueMicrotask

Writing to a file or the network for every message is slow. Batching means collecting many small jobs and doing them together. Every log() call made during the same piece of sync code should end up in one write.

function makeLogger(write) {
  let buffer = [];
  let scheduled = false;
  function flush() {
    write(buffer.join(" | "));
    buffer = [];
    scheduled = false;
  }
  return function log(message) {
    buffer.push(message);
    if (!scheduled) {
      scheduled = true;
      queueMicrotask(flush);
    }
  };
}
let writes = 0;
const log = makeLogger((line) => console.log(`write #${++writes}: ${line}`));
log("order 1 placed");
log("order 2 placed");
log("order 3 placed");
console.log("all three logged, nothing written yet");
setTimeout(() => {
  log("order 4 placed");
  log("order 5 placed");
}, 0);
all three logged, nothing written yet
write #1: order 1 placed | order 2 placed | order 3 placed
write #2: order 4 placed | order 5 placed
  • The first log queues one flush microtask; scheduled stops the next calls from queuing more.
  • flush runs right after the sync code: 3 messages, 1 write. The timer is a new task, so its 2 messages make a second batch.
  • A microtask is the right tool here: the messages are written before any other task (nothing is lost or reordered), but after the current code (so they can be grouped). Frameworks batch screen updates the same way.

Mini project 2: yield to the event loop in a long loop

A long loop holds the only thread. Here, 6 orders take 100 ms each, and a doorbell timer is due at 50 ms. First the wrong way, "yielding" with await null:

const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
function busy(msLong) {
  const start = Date.now();
  while (Date.now() - start < msLong) {}
}
async function processOrders(count) {
  for (let i = 1; i <= count; i++) {
    busy(100);
    if (i % 2 === 0) await null;
  }
  console.log("all", count, "orders done at", ms());
}
setTimeout(() => console.log("doorbell answered at", ms()), 50);
processOrders(6);
all 6 orders done at 600
doorbell answered at 600

await null only gives a microtask: the loop continues before any task, so the doorbell still waits for the whole job. Now yield (step aside so others get a turn) with a task:

const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const yieldToLoop = () => new Promise((resolve) => setImmediate(resolve));
function busy(msLong) {
  const start = Date.now();
  while (Date.now() - start < msLong) {}
}
async function processOrders(count) {
  for (let i = 1; i <= count; i++) {
    busy(100);
    if (i % 2 === 0) await yieldToLoop();
  }
  console.log("all", count, "orders done at", ms());
}
setTimeout(() => console.log("doorbell answered at", ms()), 50);
processOrders(6);
doorbell answered at 200
all 6 orders done at 600

The doorbell is answered at 200 ms, after the first two orders, instead of at the end. The total time is the same; the program just stays responsive. In a browser, use new Promise((r) => setTimeout(r, 0)) instead of setImmediate.

Your turn: predict, then run (solution)

async function a() {
  console.log("a1");
  await b();
  console.log("a2");
}
async function b() {
  console.log("b");
}
setTimeout(() => console.log("t"));
a();
Promise.resolve().then(() => console.log("p"));
console.log("s");
a1
b
s
a2
p
t

Step by step, with the 3-step method (setTimeout with no delay means 0):

Step What runs Output Queues after (microtask · task)
1 setTimeout(t) · t
2 a() starts: logs a1 a1 · t
3 a calls b(), which runs synchronously and logs b; b returns a fulfilled promise b · t
4 await b() pauses a; the rest of a is queued rest of a · t
5 Promise.resolve().then(p) rest of a, p · t
6 console.log("s"); sync code done s rest of a, p · t
7 microtask: rest of a a2 p · t
8 microtask: p p · t
9 task: t t ·

The key line is step 3: await b() calls b first (sync, so b prints right after a1), and only then awaits what it returned. a2 beats p because the rest of a was queued first.

Practice questions (with solutions)

1. Add a second await to puzzle 3, and a promise from outside. Predict the order.

async function placeOrder() {
  console.log("2 order placed");
  await null;
  console.log("4 payment checked");
  await null;
  console.log("6 chai served");
}
console.log("1 start");
placeOrder();
Promise.resolve().then(() => console.log("5 other customer"));
console.log("3 next customer");
Answer
1 start
2 order placed
3 next customer
4 payment checked
5 other customer
6 chai served

After the sync code, the queue is: rest of placeOrder, 5. The rest prints 4 and hits the second await, which queues the last part behind 5. Each await is one more trip to the back of the microtask line.

2. Microtasks inside a task. Three timers; the second one queues a nextTick and a then.

console.log("start");
setTimeout(() => console.log("timeout 1"), 0);
setTimeout(() => {
  console.log("timeout 2");
  process.nextTick(() => console.log("nextTick inside timeout 2"));
  Promise.resolve().then(() => console.log("then inside timeout 2"));
}, 0);
setTimeout(() => console.log("timeout 3"), 0);
console.log("end");
Answer
start
end
timeout 1
timeout 2
nextTick inside timeout 2
then inside timeout 2
timeout 3

Rule 2 applies after every task, not just after the script: after timeout 2, both small queues are emptied before timeout 3. (Node versions before 11 ran all due timers first; Node 11 and later behave like browsers.)

3. setImmediate inside fs.readFile, with everything else mixed in.

const fs = require("fs");
fs.readFile(__filename, () => {
  console.log("file read");
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
  process.nextTick(() => console.log("nextTick"));
  Promise.resolve().then(() => console.log("then"));
});
console.log("sync");
Answer
sync
file read
nextTick
then
immediate
timeout

sync first (the file read takes time). Inside the callback: nextTick queue, then microtasks, then the check phase (immediate), and only on the next round the timers phase (timeout).

4. An await on another async function's result.

async function getPrice() {
  console.log("fetching price");
  return 30;
}
async function main() {
  console.log("main starts");
  const price = await getPrice();
  console.log("price is", price);
}
main();
Promise.resolve()
  .then(() => console.log("tick 1"))
  .then(() => console.log("tick 2"));
console.log("main called");
Answer
main starts
fetching price
main called
price is 30
tick 1
tick 2

getPrice runs synchronously (it has no await at all) and returns an already-fulfilled promise. await on it queues the rest of main at once, before tick 1 is queued.

5. Fix the starving progress check. Rewrite the starvation program so that a heartbeat timer gets a turn between checks.

Solution
let checks = 0;
const id = setInterval(() => console.log("heartbeat after", checks, "checks"), 0);
function check() {
  checks++;
  if (checks < 3) setTimeout(check, 0);
  else setTimeout(() => clearInterval(id), 0);
}
setTimeout(check, 0);
heartbeat after 0 checks
heartbeat after 1 checks
heartbeat after 2 checks
heartbeat after 3 checks

Each check is now a task, so the heartbeat (setInterval(fn, ms) runs fn again every ms; clearInterval(id) stops it) gets a turn between checks. With queueMicrotask, all three checks would run before the first heartbeat.

6. A microtask queued by a microtask. What is in order when the timer runs?

const order = [];
Promise.resolve().then(() => {
  order.push("then A");
  queueMicrotask(() => order.push("microtask from A"));
});
Promise.resolve().then(() => order.push("then B"));
setTimeout(() => console.log(order.join(" -> ")), 0);
Answer
then A -> then B -> microtask from A

The new microtask joins the end of the line, behind then B, but still runs before the timer (step 2 keeps going until the line is empty).

Quick quiz

What does it print?

setTimeout(() => console.log("a"), 0);
new Promise((resolve) => {
  console.log("b");
  resolve();
}).then(() => console.log("c"));
console.log("d");

A) b, d, c, a B) d, b, c, a C) b, d, a, c D) a, b, c, d

Answer
b
d
c
a

A. The executor (the function passed to new Promise) runs synchronously, so b prints first, then d. The then callback is a microtask (c), and the timer is a task (a).

Interview questions

  1. What is the event loop? The loop that, whenever the call stack is empty, runs the next ready callback: first all microtasks, then one task, then microtasks again, and so on.
  2. Microtask vs macrotask? Microtasks (then, await, queueMicrotask) all run right after the current task; macrotasks (setTimeout, I/O, events) run one per loop turn.
  3. Why does setTimeout(fn, 0) not run immediately? It queues a task, which waits for the stack to empty and for all microtasks. 0 ms is a minimum, not a promise of "now" (in Node it's really 1 ms).
  4. Does async make a function run in the background? No. It runs synchronously until its first await, on the same thread; it always returns a promise.
  5. process.nextTick vs setImmediate? Despite the names, nextTick runs first (right after the current code, before promises in CommonJS); setImmediate runs in the check phase of the next loop turn.
  6. process.nextTick vs queueMicrotask? Both run before the next task; Node empties the nextTick queue before the microtask queue (in CommonJS). queueMicrotask is standard and works in browsers too.
  7. What is starvation and how do you avoid it? Microtasks (or nextTicks) that keep queuing more never let tasks run. Put repeating work in setTimeout/setImmediate.
  8. Is setTimeout(0) vs setImmediate order fixed? Not in the main module (timing-dependent); inside an I/O callback, setImmediate always runs first.
  9. How do you keep a long loop from freezing the app? Split it into chunks and yield with a task (setImmediate in Node, setTimeout in browsers), or move it to a worker thread.
  10. Walk me through an output question. The 3-step method: sync code first; then nextTick and microtask queues until empty; then one task and repeat.

Glossary

Term Meaning
Thread One line of execution; JavaScript runs your code on one
Call stack The list of functions running right now; the top one runs
Synchronous Runs now and finishes before the next line
Asynchronous Started now, finished later through a callback
Run to completion A piece of code is never interrupted halfway
Callback A function you hand over to be called later
Event loop The loop that runs the next ready callback when the stack is empty
Task / macrotask One callback from the task queue: a timer, I/O, an event, the script itself
Task queue The waiting line for tasks
Microtask A small job that runs right after the current task, before the next one
Microtask queue The waiting line for microtasks; emptied completely after each task
FIFO First in, first out: the order inside each queue
Promise A box for a value that arrives later
Settled (fulfilled / rejected) A promise that has its value (or error)
then Registers a callback; queued as a microtask when the promise settles
Executor The function passed to new Promise; runs synchronously
Async function A function marked async; sync until its first await, returns a promise
await Pause the async function; the rest is queued as a microtask
IIFE Immediately invoked function expression: a function called where it is written
queueMicrotask(fn) Put fn straight into the microtask queue
setTimeout(fn, ms) Queue fn as a task after at least ms milliseconds
setInterval(fn, ms) / clearInterval Run fn every ms / stop it
process.nextTick(fn) Node only: run fn right after the current code
nextTick queue Node's own queue, emptied before the microtask queue (in CommonJS)
Starvation One kind of work never runs because another keeps cutting in
setImmediate(fn) Node only: run fn in the check phase of the loop
Phase One stage of Node's loop: timers, poll (I/O), check (setImmediate), …
I/O Input/output: reading files, network, keyboard
fs.readFile(path, cb) Read a file; cb runs from the poll phase
__filename The path of the current CommonJS file
CommonJS Node's older module format (require); a .js file with no import/export/top-level await
ES module The standard module format (import/export); .mjs or top-level await
Top-level await await outside any function; makes Node run the file as an ES module
vm module Node module that runs code in a separate global object
Rendering The browser painting the screen; happens between tasks
Batching Collecting many small jobs and doing them together
Yield (to the event loop) Pause long work with a task so other callbacks get a turn
Busy waiting A loop that spins until time passes; blocks the thread

Summary

  • JavaScript runs one thing at a time, to completion. Callbacks wait in queues; the event loop runs them when the call stack is empty.
  • Tasks (setTimeout, I/O, setImmediate) run one per turn. Microtasks (then, await, queueMicrotask) all run after every task, including new ones added on the way. In Node's CommonJS files, the nextTick queue goes even before them; in ES modules, then comes before nextTick.
  • An async function runs synchronously until its first await; each then in a chain is queued only when the previous one settles; the new Promise executor runs at once.
  • Microtasks that never stop starve timers; repeat work with tasks. setImmediate vs setTimeout(0) is only fixed inside I/O callbacks.
  • The 3-step method: sync code → nextTick + microtasks until empty → one task → repeat. It predicted 1 4 9 7 5 8 2 3 6.
  • Next episode: recursion questions: sum of digits, power, all permutations of a string, all subsets, and what happens when the call stack runs out of room.