Introduction & Syntax
Event Loop · Study material
JavaScript runs your code on a single thread, yet it handles timers, clicks and network replies without freezing. The event loop makes that possible: synchronous code runs on the call stack, finished asynchronous work waits in queues, and the loop feeds the next callback in only when the stack is empty. Knowing the rules – sync code first, then every microtask, then one task, then microtasks again – lets you predict the output of any async snippet, which is why "what does this print?" event-loop puzzles appear in almost every JavaScript interview and placement test. After the guide, test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – each one run on Node.js.
The pieces
| Part | What it holds | Examples |
|---|---|---|
| Call stack | The functions running right now | your script, a callback being executed |
| Web APIs / Node.js APIs | Work happening outside JavaScript | timers counting down, network requests, file reads |
| Task (macrotask) queue | Callbacks ready to run, one per loop turn | setTimeout, setInterval, events, I/O, setImmediate |
| Microtask queue | Small follow-up jobs, all run before the next task | promise then/catch/finally, await continuations, queueMicrotask, MutationObserver |
The order: sync → microtasks → task
The script itself is the first task. When it finishes, the loop empties the microtask queue, then takes one task, then empties the microtask queue again, and so on. That is why a promise callback beats setTimeout(…, 0) even when the timer was scheduled first.
console.log("1. sync – runs on the call stack now");
setTimeout(() => console.log("4. task (macrotask) – a timer callback"), 0);
Promise.resolve().then(() => console.log("3. microtask – a promise callback"));
console.log("2. sync – still the same script");
1. sync – runs on the call stack now 2. sync – still the same script 3. microtask – a promise callback 4. task (macrotask) – a timer callback
Microtasks drain completely
Microtasks added while the queue is being emptied run in the same round – before any task. (This also means an endless chain of microtasks can starve timers and rendering.)
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => {
console.log("micro 1");
queueMicrotask(() => console.log("micro 3 – added by micro 1, still before the timer"));
});
queueMicrotask(() => console.log("micro 2"));
micro 1 micro 2 micro 3 – added by micro 1, still before the timer timer
Microtasks run after every task
It is not "all timers, then all promises": after each single task, its microtasks run before the next task begins.
// After EVERY task the microtask queue is emptied before the next task starts
setTimeout(() => {
console.log("task 1");
Promise.resolve().then(() => console.log(" microtask from task 1"));
}, 0);
setTimeout(() => console.log("task 2"), 0);
task 1 microtask from task 1 task 2
Timers are a minimum delay
setTimeout(fn, ms) means "queue fn after at least ms". Timers fire in order of their due time; equal delays keep the order they were scheduled in. The delay is never a guarantee: the callback waits until the stack is free.
const log = [];
setTimeout(() => log.push("30 ms"), 30);
setTimeout(() => log.push("10 ms"), 10);
setTimeout(() => log.push("20 ms"), 20);
setTimeout(() => log.push("10 ms (second)"), 10); // same delay → order of scheduling
setTimeout(() => console.log(log), 50);
[ '10 ms', '10 ms (second)', '20 ms', '30 ms' ]
Blocking the thread
While synchronous code runs, nothing else can – not timers, not clicks, not rendering. A long loop makes the page freeze and makes every timer late.
const start = Date.now();
setTimeout(() => {
const waited = Date.now() - start;
console.log(`timer asked for 0 ms, ran after ≥ 100 ms: ${waited >= 100}`);
}, 0);
// A long synchronous loop keeps the call stack busy: nothing else can run
while (Date.now() - start < 100) { /* busy for 100 ms */ }
console.log("loop finished");
loop finished timer asked for 0 ms, ran after ≥ 100 ms: true
async/await in the event loop
An async function runs synchronously up to its first await; everything after it is scheduled as a microtask.
async function task(name) {
console.log(`${name}: start (sync)`);
await null; // the rest becomes a microtask
console.log(`${name}: after await (microtask)`);
}
setTimeout(() => console.log("timeout (task)"), 0);
task("A");
task("B");
console.log("script end");
A: start (sync) B: start (sync) script end A: after await (microtask) B: after await (microtask) timeout (task)
Node.js extras
Node.js has the same rules plus two extra queues. process.nextTick callbacks run before promise microtasks; setImmediate runs in the "check" phase, right after I/O callbacks. The loop's phases are: timers → pending callbacks → poll (I/O) → check (setImmediate) → close callbacks, with nextTick and microtask queues emptied between every callback. In the main script the order of setTimeout(fn, 0) and setImmediate is not guaranteed; inside an I/O or timer callback, setImmediate always comes first.
Common mistakes
- Expecting setTimeout(fn, 0) to run immediately – it waits for the stack and for all microtasks.
- Reading a value that an async callback has not set yet – the callback runs later.
- Busy-wait "sleep" loops – they freeze everything; use await with a timer promise.
- try/catch around setTimeout – it cannot catch errors thrown later in the callback.
- Passing setTimeout(fn()) – calls fn now and passes its result.
- Endless microtask loops – starve timers, I/O and rendering.
- Calling a callback sometimes synchronously, sometimes asynchronously – unpredictable order ("releasing Zalgo").
Key points to remember
- One thread, one call stack: one piece of JavaScript runs at a time.
- Sync code → all microtasks → one task → all microtasks → …
- Promises, await and queueMicrotask are microtasks; timers, events and I/O are tasks.
- setTimeout's delay is a minimum, not an exact time.
- Long synchronous work blocks everything – chunk it or move it to a Web Worker.
- Node.js: nextTick before promises; setImmediate in the check phase.
Frequently asked questions
If JavaScript is single-threaded, who counts the timers?
The browser or Node.js (the host environment). They run timers, network and file work on their own threads and queue your callback when it is ready.
When does the browser repaint the page?
Between tasks, after the microtask queue is empty (usually about 60 times a second). requestAnimationFrame callbacks run just before a repaint.
How do I run heavy work without freezing the page?
Split it into chunks with setTimeout or scheduler APIs, or run it in a Web Worker, which has its own thread and event loop.
Where can I learn more?
Read the event loop, async and await and Promises in the JavaScript tutorial, then practise with the exercises below.