A website can let you type or click other buttons while it waits for an API response. The whole page does not have to stop until the response arrives.
But if JavaScript is single-threaded, how does this work?
On the browser’s main thread, JavaScript runs one piece of code at a time. The browser manages waiting for timers and network responses, allowing other code to continue. The event loop helps determine when ready work runs.
Let’s look at the parts shown in the illustration.
1. Call stack: the work running now
When a function is called, it gets a frame on the call stack. If it calls another function, the new frame goes on top and that function runs first. Its frame leaves the stack when it finishes.
2. Web APIs: work managed by the browser
Browser APIs manage operations such as scheduling a timer with setTimeout() and sending a request with fetch().
Setting a three-second timeout does not pause JavaScript for three seconds. It registers the timer with the browser and lets the following code continue.
3. Task queues: timers and user interactions
When a timer becomes due, its callback is scheduled as a task. A callback is a function that is called later to perform some work.
Handlers for user interactions such as button clicks are also scheduled through tasks. Ready work cannot simply interrupt the JavaScript that is currently running.
4. Microtask queue: Promise handlers
Promise handlers such as .then() and .catch() use the microtask queue. Since fetch() returns a Promise, its .then() handler runs as a microtask once the Promise settles.
After the current task finishes, pending microtasks are drained before the next task runs. If a microtask adds another microtask, that new work is processed during the same drain as well.
5. Event loop: coordinating the next work
The basic flow is to finish the current task, then drain pending microtasks. At appropriate rendering opportunities, the browser can update the screen. It then continues processing tasks, repeating the cycle.
Understanding these parts helps explain why setTimeout(), Promises, and async/await run in the order you observe, including cases where that order differs from your first expectation.

