โ† Over the wire ยท all materialsPlayground
Async

Event loop lab

JavaScript runs one thing at a time, on one call stack. Waiting (for the network, for a timer) happens in the browser; when it's done, a callback is queued. Step through two programs and watch where each piece of work is: on the call stack, in the browser, in the microtask queue (promise callbacks, resuming after await) or in the task queue (timers, events).

The rules

  1. Code on the call stack runs to the end. Nothing interrupts it: not a click, not a timer, not a response.
  2. When the stack is empty, the event loop runs every microtask, including ones queued by microtasks.
  3. Then it takes one task from the task queue, and the browser may render. Repeat.
  4. await suspends only its own function: the function's frame leaves the stack, the caller carries on, and resuming is a microtask.

Try this

  1. Before stepping through "timer ยท promise ยท fetch", write down the order of the letters. Which one surprised you?
  2. Why does D print before B, although setTimeout was called first?
  3. In "async / await", at which step is loadStalls no longer on the stack, and what is still holding on to its variables?
  4. What would happen to the page if the request on line 3 were synchronous and took two seconds?