Study notes · 10% of the exam
The Event Loop
One main thread runs tasks one at a time; microtasks run between them. That explains most ordering puzzles.
Key points
- 1
The current script (a task) always runs to completion before anything else.
- 2
After each task, the microtask queue (promise callbacks,
queueMicrotask) is drained completely. - 3
Then the next task runs: a timer, an event, a message. Rendering happens between tasks.
- 4
Long synchronous work blocks input and rendering; split it up or move it to a Web Worker.
Common traps
setTimeout(fn, 0)does not run immediately. It waits for the current task and all microtasks.
Read the source
Further reading
Suggest a resource- javascript.info: Event loop, microtasks and macrotasks(opens in a new tab)How tasks and microtasks are queued and run, with ordering examples.Articlejavascript.infoEditor’s pick
- What the heck is the event loop anyway? (Philip Roberts)(opens in a new tab)The call stack, Web APIs and the callback queue visualised step by step.Videoyoutube.comEditor’s pick
Test yourself on The Event Loop
Ten questions, with the answer and explanation after each one.