Asynchronous JS

The event loop

How single-threaded JavaScript handles async without blocking.

advanced Experienced

JavaScript runs on a single thread with one call stack. Long-running work would freeze the UI, so async tasks are handed off and their callbacks queued for later.

The event loop is a barista serving one order at a time: it finishes every quick "microtask" refill before calling the next "macrotask" customer.

Key concepts

1
The event loop repeatedly checks: is the call stack empty? If so, it drains the microtask queue (promise callbacks, queueMicrotask) completely, then takes one task from the macrotask queue (setTimeout, I/O, UI events) and runs it.
event loopmicrotask queueonemacrotask queuequeueMicrotask
2
This ordering is why a resolved promise's .then always runs before a setTimeout(…, 0) scheduled at the same time — microtasks have priority over macrotasks.
.thensetTimeout(…, 0)