Learning on Web Dev Open is free for all.

Systems Thinking > One thread, several queuesThe event loop, for real
Phase 03One thread, several queues140 of 434

The event loop, for real

A page that prints the order things actually happened in. One of the lines it prints is a lie your code is telling you.

Build50 minAI pair
Phase 03 · Lesson 02

The event loop, for real

AI: pair~50 min

You know that setTimeout is "later". This page prints the order it actually happens in, and one of the lines it prints is a lie your code is telling you.

Beat 1: Build it

The page below runs eight bits of asynchronous work and writes each one into the list as it completes. Read the source first and write down the order you expect. Then look at what it printed. The gap between the two lists is the lesson, and the gap is bigger than most people expect even after they have read the spec.

Use the model as a pair here, not to fix anything yet, but to argue with. Paste the source and your predicted order, ask it to explain the difference, and then check its explanation against the running page rather than believing it. Models are fluent about the event loop and still get the boundary between the microtask queue and the task queue wrong, usually by claiming a promise resolved by a timer is a microtask. It is a task that then schedules a microtask, and the difference shows up in this list.

One entry in the list is a straightforward bug rather than a surprise: a line that claims work has finished when none of it has. It is the single most common async mistake in production JavaScript, it never throws, and it looks correct in review.

Ask the community

Loading…

Workbench

You should now be able to

  • Predict a real execution order before running it
  • Recognise the async bug that never throws
Ask the community

Loading…