Build a tiny model of the event loop with a call stack-free "run" method, a task queue and a microtask queue: after each task, drain all microtasks. Use it to replay a typical interview snippet.
class EventLoop {
tasks = [];
microtasks = [];
log = [];
setTimeout(fn) { this.tasks.push(fn); }
queueMicrotask(fn) { this.microtasks.push(fn); }
drainMicrotasks() {
while (this.microtasks.length) this.microtasks.shift()(); // includes ones added while draining
}
run(script) {
script(); // the script itself is the first task
this.drainMicrotasks();
while (this.tasks.length) {
this.tasks.shift()();
this.drainMicrotasks(); // after EVERY task
}
return this.log.join(" → ");
}
}
const loop = new EventLoop();
const out = (s) => loop.log.push(s);
console.log(loop.run(() => {
out("sync1");
loop.setTimeout(() => { out("task1"); loop.queueMicrotask(() => out("micro-in-task1")); });
loop.setTimeout(() => out("task2"));
loop.queueMicrotask(() => { out("micro1"); loop.queueMicrotask(() => out("micro2")); });
out("sync2");
}));
sync1 → sync2 → micro1 → micro2 → task1 → micro-in-task1 → task2
The model captures the two rules that explain most puzzles: the microtask queue is drained completely, and it is drained after every single task.