Track 02 · Lesson 10 of 17Inside the browser

Track 02 · Inside the browser

The event loop

Lesson 10 of 17· 9 min

JavaScript does one thing at a time. Timers, network calls and promises never interrupt it: their callbacks wait in queues until the call stack is empty. Microtasks, like promise callbacks, always run before the next task, like a timer or a click. Guess the output, then step through.

Guess, then step through

Three small programs

Your guess: click the lines in the order you think they’ll print

console.log("A: start");
setTimeout(() => {
console.log("D: timeout");
}, 0);
Promise.resolve().then(() => {
console.log("C: promise");
});
console.log("B: end");

Call stack

Browser APIs

Microtask queue

Task queue

Console

(nothing printed yet)
Step 1 of 10

The whole script is the first task. It starts running on the call stack.

The four boxes#

  • The call stack is what's running right now. There's only one, which is why JavaScript is "single-threaded".
  • Browser APIs do the waiting outside JavaScript: timers, network requests, listening for clicks.
  • The microtask queue holds promise callbacks, code after an await, and anything passed to queueMicrotask.
  • The task queue holds timer callbacks, events like clicks, and messages.

The order of play#

  1. Run the current task until the stack is empty. The first task is your script.
  2. Run every microtask, including any new ones added along the way.
  3. Maybe render a frame.
  4. Take one task from the task queue, and go back to step 1.

That's why setTimeout(fn, 0) doesn't mean "now": it means "after everything that's already queued, and after all the microtasks".

Check yourself

What does this print? setTimeout(() => log('A'), 0); Promise.resolve().then(() => log('B')); log('C');