DEV Community

Cover image for The JavaScript event loop, explained through 5 output questions
Yash Maheshwari
Yash Maheshwari

Posted on Originally published at jsprep.pro

The JavaScript event loop, explained through 5 output questions

"Explain the event loop" comes up in almost every frontend interview. The follow-up is nearly always the same: here's a snippet, what does it print?

Knowing the words (call stack, task queue, microtasks) isn't enough for that. You need one rule and the habit of tracing code with it. This post gives you the rule, then five output questions to practise it on. Try each one before reading the answer.

The model in 60 seconds

JavaScript runs on one thread with one call stack. Only one function runs at a time.

Slow work, like timers, network requests and clicks, is handed to the browser (or Node). When that work finishes, its callback waits in a queue. There are two queues that matter:

Queue What goes in it How it runs
Microtask queue .then / .catch / .finally callbacks, code after await, queueMicrotask Emptied completely after each task, including microtasks added along the way
Task queue (macrotasks) setTimeout / setInterval callbacks, DOM events, MessageChannel One per turn of the loop

One turn of the event loop:

  1. Run one task (the first is your whole script) until the call stack is empty.
  2. Run every microtask.
  3. Let the browser paint, if it's time to.
  4. Take the next task and repeat.

That's the whole rule. Now let's use it.

Question 1: promise vs timeout

console.log('start')

setTimeout(() => console.log('timeout 1'), 0)
setTimeout(() => console.log('timeout 2'), 0)

Promise.resolve()
  .then(() => console.log('promise 1'))
  .then(() => console.log('promise 2'))

console.log('end')
Enter fullscreen mode Exit fullscreen mode

Answer
start, end, promise 1, promise 2, timeout 1, timeout 2
  • Synchronous code first: start and end log. Both timeouts go to the task queue, and the first .then goes to the microtask queue.
  • Stack empty, so drain microtasks: promise 1 runs, and its return queues the second .then. The microtask queue still isn't empty, so promise 2 runs too.
  • Only now do tasks run, one per turn: timeout 1, then timeout 2.

A delay of 0 doesn't mean "now". It means "in a later task".


Question 2: the Promise constructor

console.log(1)

setTimeout(() => console.log(2))

new Promise(resolve => {
  console.log(3)
  resolve()
}).then(() => console.log(4))

console.log(5)
Enter fullscreen mode Exit fullscreen mode

Answer
1, 3, 5, 4, 2

The function you pass to new Promise (the executor) runs synchronously, right away. Only the .then callback is async. That's why 3 logs between 1 and 5.


Question 3: what await actually does

async function main() {
  console.log('main: before await')
  await Promise.resolve()
  console.log('main: after await')
}

console.log('before main')
main()
console.log('after main')
Enter fullscreen mode Exit fullscreen mode

Answer
before main, main: before await, after main, main: after await

An async function runs synchronously until its first await. At that point it pauses, and the rest of the function is queued as a microtask. Control returns to the caller, so after main logs first. Then the microtask resumes main.


Question 4: microtasks between tasks

setTimeout(() => {
  console.log('timeout 1')
  Promise.resolve().then(() => console.log('micro inside timeout 1'))
}, 0)

setTimeout(() => console.log('timeout 2'), 0)
Enter fullscreen mode Exit fullscreen mode

Answer
timeout 1, micro inside timeout 1, timeout 2

Microtasks drain after every task, not only after the script. The promise queued inside the first timeout runs before the second timeout gets its turn.


Question 5: the one that catches seniors

Promise.resolve()
  .then(() => {
    console.log('A')
    return Promise.resolve('B')
  })
  .then(v => console.log(v))

Promise.resolve()
  .then(() => console.log('C'))
  .then(() => console.log('D'))
Enter fullscreen mode Exit fullscreen mode

Answer
A, C, D, B

Most people guess A, B, C, D or A, C, B, D.

When a .then handler returns a promise, the outer promise doesn't settle immediately. The spec adds two extra microtask hops to adopt the returned promise's state. While those hops happen, the other chain keeps moving, so C and D log first.

The takeaway: return Promise.resolve(x) inside .then is not the same as return x. It costs extra ticks.


Why this matters outside interviews

  • Long synchronous code freezes everything. While the stack is busy, no microtasks, tasks, clicks or paints can happen. Split heavy work into chunks, or move it to a Web Worker.
  • Endless microtasks freeze the page too. If each microtask queues another, the queue never empties and the browser never paints.
  • Choosing a scheduler:
    • queueMicrotask or a promise: "as soon as the current code finishes".
    • setTimeout: "in a later task", which gives the browser a chance to handle events and paint in between.
    • requestAnimationFrame: "right before the next paint", for visual updates.

The five facts

  1. JavaScript runs one thing at a time.
  2. Synchronous code always finishes before any queue is checked.
  3. After each task, the entire microtask queue drains.
  4. Then one task runs, and microtasks drain again.
  5. Promise callbacks and await continuations are microtasks. Timers and events are tasks. Microtasks always win.

Trace every snippet with these, line by line, and event loop questions stop being guesswork.


I run JSPrep Pro, where you practise questions like these by predicting the output and then running the code. Five more event loop puzzles, free:

The full topic guide, with more interview questions: JavaScript event loop interview questions.

Top comments (0)