Four orders at the warung: console.log, queueMicrotask, .then and setTimeout(0), each scheduled its own way; guess the order, then the browser prints the four…
Why it matters
Guessing this order wrong breeds the most confusing async bugs: state updated "late", logs in a strange order, a frozen page. Knowing "every microtask is drained before one task" explains almost every timing surprise in JavaScript, and when queueMicrotask starves the task queue instead.
The key idea
Every microtask is drained before a single task runs
Common mistakes
Writing setTimeout(fn, 0) and expecting fn to run first, while it keeps losing to microtasks It is a task: it waits for the script to finish and every microtask to drain. For "as soon as possible, after this code", use queueMicrotask(fn).
A microtask that keeps scheduling itself: the page freezes, never repainted The microtask queue is never empty, so no task (repainting included) gets a turn. Break heavy work up with setTimeout or scheduler.yield().
Using queueMicrotask to wait until after a render, but the render is not on screen yet Microtasks run before the browser gets to paint: they give it no breath. To wait for the next frame use requestAnimationFrame; for after the paint, a setTimeout inside it.
Try it in this playground
Watch a microtask jump ahead of setTimeout 0 Step until a note is taken while a villager still waits outside.
queueMicrotask and .then in one queue Both kinds of note hang on the same string, in the order queued.
Note '2+' runs between two tasks Open A note from '2': a microtask from a task runs before the next task.
A chain of microtasks starves the tasks Open Notes without end and step through the chain.