Appearance
The Event Loop
60. What is the Event Loop in JavaScript?
The short answer
The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work. It repeats one simple cycle: run the current task until the call stack is empty, then run every waiting microtask, such as promise callbacks, then let the host do its own work, such as rendering in a browser, and then take the next task, such as a timer or I/O callback, from the task queue. Because of this loop, slow work never blocks the thread; only your own long-running code can.
Each part, in plain words:
- Call stack: where your code actually runs, one function at a time (question 3).
- Host APIs: timers, network, disk. They do the waiting outside your code.
- Task queue, also called the macrotask or callback queue: callbacks for timers, I/O completions and user events, waiting their turn.
- Microtask queue: callbacks for promises and
queueMicrotask, which have priority over tasks (question 62). - The loop itself: checks whether the stack is empty and decides what runs next.
The one rule that explains most behaviour: nothing interrupts code that is running. A timer that is "due" just waits in the queue until the current code, and all microtasks after it, have finished.
ts
setTimeout(() => console.log('timer'), 0)
const end = Date.now() + 2000
while (Date.now() < end) {} // busy for 2 seconds
console.log('loop done')
// loop done (after 2 s)
// timer (only then)The timer was due after 0 ms, but it ran after 2 seconds, because the stack was never empty (question 65).
Browser versus Node.js. The idea is the same. Node.js's event loop, built on libuv, splits the task queue into several phases: timers, I/O callbacks, setImmediate and close callbacks. It also has process.nextTick, which runs even before promise microtasks. Those details are in the Node.js module.
61. What are the call stack, task queue, and microtask queue?
The short answer
The call stack holds the functions running right now. The task queue holds callbacks that are ready to run as separate tasks, such as timer callbacks, I/O completions and click handlers. The microtask queue holds small follow-up jobs, mainly promise reactions such as .then callbacks and code after await. After each task, and whenever the stack empties, the engine runs every microtask before taking the next task, so microtasks always run first.
| Call stack | Microtask queue | Task queue | |
|---|---|---|---|
| Holds | Running functions | Promise callbacks, await continuations, queueMicrotask | Timers, I/O callbacks, events, messages |
| Order | Last in, first out | First in, first out | First in, first out, per source |
| When it runs | Now | As soon as the stack is empty, all of them | One per lap of the loop |
| Fed by | Function calls | Settled promises | Host APIs when work finishes |
Watching all three:
ts
console.log('A') // (1) stack
setTimeout(() => console.log('B'), 0) // (2) task queue
Promise.resolve().then(() => console.log('C')) // (3) microtask queue
console.log('D') // (4) stack
// A, D, C, B- Runs at once.
- Registers a timer. Its callback goes to the task queue.
- The promise is already resolved, so its callback goes to the microtask queue right away.
- Runs at once.
When the script finishes and the stack is empty, all microtasks run, so C. Only then does the loop take the next task, so B.
await is a microtask too. Everything after an await in an async function is scheduled as a microtask when the awaited promise settles (question 53).
62. What is the difference between microtasks and macrotasks?
The short answer
Microtasks are small jobs that must run as soon as the current code finishes: promise reactions, await continuations, queueMicrotask callbacks and MutationObserver callbacks. Macrotasks, usually just called tasks, are larger units of work such as timer callbacks, I/O callbacks, user events and setImmediate in Node.js. After every macrotask, the engine empties the whole microtask queue, including microtasks added during that process, before moving to the next macrotask.
| Microtasks | Macrotasks | |
|---|---|---|
| Examples | .then, .catch, await, queueMicrotask, MutationObserver | setTimeout, setInterval, I/O, click events, MessageChannel, setImmediate |
| How many per lap | All of them, until the queue is empty | One |
| Can delay rendering | Yes, if there are many | Rendering can happen between them |
| Purpose | Finish follow-up work before anything else happens | Schedule independent work |
Why two queues? Promise callbacks need to run soon after the code that resolved them, before the page repaints or another event is handled, so the program never sees a half-updated state. Timers and events are independent work that can wait their turn.
Microtasks added by microtasks run in the same round:
ts
setTimeout(() => console.log('task'), 0)
Promise.resolve().then(() => {
console.log('micro 1')
Promise.resolve().then(() => console.log('micro 2')) // added during the drain
})
// micro 1, micro 2, taskmicro 2 was added while microtasks were running, so it also runs before the timer. This is the root of microtask starvation (question 64).
63. What does this code print?
The short answer
Work through it with three lists: what runs now on the call stack, what goes to the microtask queue, and what goes to the task queue. Synchronous lines print first, in order. Then every microtask prints, in the order they were queued, including any they add. Then the first task prints, followed by any microtasks it creates, then the next task. Code before the first await in an async function is synchronous.
The puzzle interviewers love:
ts
console.log('1')
setTimeout(() => console.log('2'), 0)
Promise.resolve().then(() => console.log('3'))
async function run() {
console.log('4')
await null
console.log('5')
}
run()
new Promise((resolve) => {
console.log('6')
resolve(null)
}).then(() => console.log('7'))
setTimeout(() => {
console.log('8')
Promise.resolve().then(() => console.log('9'))
}, 0)
console.log('10')Answer: 1, 4, 6, 10, 3, 5, 7, 2, 8, 9
Line by line:
console.log('1')runs: prints 1.- The first
setTimeoutputs "print 2" in the task queue. Promise.resolve().then(...)puts "print 3" in the microtask queue.run()starts. Code before the firstawaitis synchronous: prints 4.await nullpausesrunand queues "the rest of run", which prints 5, as a microtask.- The
new Promiseexecutor runs synchronously: prints 6.resolveis called, so "print 7" is queued as a microtask. - The second
setTimeoutputs its callback in the task queue, behind the first. console.log('10')runs: prints 10. The stack is now empty.- The microtasks run in the order they were queued: 3, 5, 7.
- The first task runs: prints 2. It added no microtasks.
- The second task runs: prints 8, and queues "print 9" as a microtask, which runs before any further task: 9.
The traps this puzzle tests:
- The
new Promiseexecutor runs immediately, not later. - Code in an async function before the first
awaitis synchronous. setTimeout(…, 0)always loses to promise callbacks queued in the same round.- A microtask created inside a task runs before the next task.
64. What is queueMicrotask, and can microtasks starve the event loop?
The short answer
queueMicrotask(fn) schedules a function as a microtask directly, without creating a promise, so it runs right after the current code and before any timer or event. Because the engine drains the microtask queue completely before moving on, a microtask that keeps scheduling more microtasks never lets the loop reach the task queue: timers never fire, I/O callbacks never run and, in a browser, the page never repaints. That is microtask starvation.
ts
let flushing = false
const pendingLogs: string[] = []
function logLater(line: string) {
pendingLogs.push(line)
if (!flushing) {
flushing = true
queueMicrotask(() => { // (1)
console.log(pendingLogs.join('\n'))
pendingLogs.length = 0
flushing = false
})
}
}
logLater('cart updated')
logLater('price recalculated') // (2)- Batch work at the end of the current code: several calls in the same synchronous run are written out together, once.
- Only one flush is scheduled for both calls.
Starvation:
ts
setTimeout(() => console.log('timer finally ran'), 0)
function spin() {
queueMicrotask(spin) // schedules itself again, for ever
}
spin()
// the timer never runs; the page or process is frozenEach microtask adds another before the queue is empty, so the loop never gets past step ② (question 60). The same can happen with a recursive .then chain or an endless async loop that never awaits anything slow.
The fix: if work must repeat, yield to the task queue between rounds with setTimeout(fn, 0), setImmediate in Node.js, or scheduler.yield() in Chromium-based browsers, so timers, I/O and rendering get their turn.
65. Why does a long loop freeze the page or the server?
The short answer
Because JavaScript runs your code on one thread, and the event loop cannot move on until the current task finishes. A loop that takes two seconds holds the call stack for two seconds. During that time no click is handled, no frame is painted, no timer fires and, in Node.js, no other request is served. The fixes are to make the work smaller, split it into chunks that yield back to the loop, or move it to a worker thread.
In a server, this is a production outage:
ts
app.get('/report', (req, res) => {
const rows = loadAllOrders() // say 2 million rows in memory
const totals = rows.reduce(sumByCustomer, {}) // (1) 3 seconds of CPU
res.json(totals)
})- Three seconds of pure computation. Every other request to this Node.js process, including health checks, waits behind it. Under load, the health checks fail and the load balancer marks the server as down.
Three ways out:
| Approach | How | Good for |
|---|---|---|
| Do less | Compute in the database with GROUP BY, cache results, paginate | Most reporting cases |
| Chunk and yield | Process 10,000 rows, then await a setImmediate or setTimeout, then continue | Medium work that must stay in this process |
| Move it off the main thread | A worker thread, a job queue, or a separate service | Heavy CPU work, such as images, PDFs, crypto |
Chunking, in code:
ts
const yieldToLoop = () => new Promise((r) => setImmediate(r))
async function sumInChunks(rows: { customerId: string; total: number }[]) {
const totals = new Map<string, number>()
for (let i = 0; i < rows.length; i++) {
const r = rows[i]
totals.set(r.customerId, (totals.get(r.customerId) ?? 0) + r.total)
if (i % 10_000 === 0) await yieldToLoop() // let other requests run
}
return totals
}Every 10,000 rows, the function pauses and lets the event loop serve other work, then continues. The total time is a little longer, but the server stays responsive.
In a browser, the same applies to the main thread: long tasks over 50 ms make the page feel stuck. Web Workers take heavy work off the main thread. Worker threads, the cluster module and child processes for Node.js are compared in the Node.js module.