Advanced 12 min

The event loop and microtasks

The event loop runs queued work after the current JavaScript stack finishes.

How it works

The current script owns the stack until it returns. A resolved Promise adds a callback to the microtask queue, while setTimeout schedules timer work. The sample therefore logs A first, runs the queued Promise callback for B, and only then lets the timer print C.

Walk through an example

Synchronous code finishes first. A resolved Promise queues a microtask. A timer queues a later task. At the microtask checkpoint, Promise callbacks usually run before a pending zero-delay timer.

What to watch for

A zero-delay timer sets a minimum wait, not an exact delivery time. Long synchronous work still blocks the current thread.

Code example

console.log('A');
setTimeout(() => console.log('C'), 0);
Promise.resolve().then(() => console.log('B'));

Check your understanding

What order do the logs appear in?

See the example and explanation
Worked example
Given Log A, queue a zero-delay timer that logs C, then queue a resolved Promise that logs B.
Answer A, B, C

The current script logs A. The microtask logs B before the timer task can log C.

Open practice problem
Next lessonIterables and generators