JavaScript
Series · Under the Hood
The event loop, explained without hand-waving
Microtasks, macrotasks, and why your setTimeout(0) doesn't run when you think. A mental model you can actually reason with.
May 2, 20261 min read
One thread, many tricks
JavaScript runs your code on a single thread. Concurrency is an illusion built from a queue and a scheduler.
The order that matters
- Run the current synchronous stack to completion.
- Drain all microtasks (promises, queueMicrotask).
- Render, if the browser wants to.
- Take one macrotask (timers, I/O) and repeat.
js
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// 1, 4, 3, 2A microtask that schedules another microtask can starve the render step. Keep them cheap.
Try the interactive version on the Demos page to watch tasks flow through the queues in real time.
#JavaScript
#Runtime
#Async