Event loop in js
The Event Loop & Concurrency Model in JavaScript
Call Stack, Web APIs, Task Queue, Microtask Queue, and Browser Rendering
1. The Problem: JavaScript Is Single-Threaded
Imagine you're using a website.
You click a button to load some data. The browser sends a request to a server. While the request is running, you can still scroll the page, open a menu, or click another button.
But here's an interesting question:
If JavaScript executes one operation at a time, how can it handle multiple activities without freezing the entire website?
To understand this, we first need to understand how JavaScript executes code.
JavaScript is traditionally described as a single-threaded language in the browser. Its main execution thread has one Call Stack, meaning it can execute only one piece of JavaScript at a time on that thread.
Consider this example:
console.log("First");
console.log("Second");
console.log("Third");
Output:
First
Second
Third
Nothing surprising here.
JavaScript executes each statement in order. It doesn't move to the next statement until the current synchronous operation finishes.
But what happens when an operation takes several seconds?
For example:
console.log("Start");
const start = Date.now();
while (Date.now() - start < 3000) {
// Blocking the main thread for approximately 3 seconds
}
console.log("Finished");
console.log("End");
Output:
Start
Finished
End
For approximately three seconds, JavaScript is busy executing the while loop.
During this time, the browser's main thread cannot process other JavaScript callbacks or update the page through its normal rendering process.
This is called blocking the main thread.
And this is exactly the problem the Event Loop's surrounding runtime mechanisms help us avoid.
2. The Restaurant Analogy: The Busy Restaurant and the Diligent Waiter
Imagine a restaurant with one master chef.
The chef can prepare only one dish at a time. This is our Call Stack.
Now imagine customers ordering dishes that require different amounts of time.
Some dishes are prepared immediately.
Some need to bake in an oven.
Some require ingredients to arrive from another location.
Some customers need to be notified when their orders are ready.
If the chef personally waits for every pie to bake, the entire kitchen stops working.
Instead, the chef gives the baking task to an assistant and continues preparing another dish.
When the pie is ready, the assistant places a notification in the appropriate order queue.
JavaScript works with a similar arrangement.
Restaurant | JavaScript |
|---|---|
Master chef | Call Stack |
Chef's kitchen | JavaScript execution environment |
Baking assistant | Browser runtime services |
VIP order tray | Microtask Queue |
Regular order tray | Task Queue |
Diligent waiter | Event Loop |
The chef doesn't stop working to wait for the oven.
Similarly, JavaScript can delegate certain asynchronous operations to the surrounding runtime and continue executing other code.
When the Call Stack becomes empty, the Event Loop helps determine which queued work should run next.
The important rule: After a task finishes and its microtask checkpoint begins, the runtime processes the microtask queue until it is empty before moving on to another task.

3. Understanding the Call Stack
Before understanding the Event Loop, let's understand the Call Stack.
The Call Stack is a data structure that keeps track of currently executing function calls.
It follows the LIFO principle:
Last In, First Out.
The last function added to the stack is the first one removed.
Consider:
function first() {
console.log("First function");
}
function second() {
first();
console.log("Second function");
}
function third() {
second();
console.log("Third function");
}
third();
Output:
First function
Second function
Third function
Let's understand how the stack changes.
Step 1:
JavaScript starts executing third().
| third() |
|---------|
Step 2:
Inside third(), JavaScript calls second().
| second() |
| third() |
|----------|
Step 3:
Inside second(), JavaScript calls first().
| first() |
| second() |
| third() |
|----------|
Step 4:
first() completes and is removed from the stack.
Then second() completes, followed by third().
Eventually, the stack becomes empty.
This is how JavaScript tracks synchronous execution.
4. What Are Web APIs?
Now let's return to our original problem.
What happens when JavaScript encounters an asynchronous operation such as:
setTimeout(() => {
console.log("Timer completed");
}, 2000);
Does JavaScript sit idle for two seconds?
No.
In a browser, JavaScript interacts with facilities provided by the browser runtime, often called Web APIs.
Examples include:
Timers such as
setTimeout()andsetInterval().Network operations such as
fetch().DOM event handling.
Browser observation APIs such as
MutationObserver.
These facilities handle work outside the normal synchronous execution of the JavaScript Call Stack.
The exact implementation depends on the browser and operation. It is not accurate to assume that every asynchronous operation runs on a separate background C++ thread.
Let's see what happens with a timer.
console.log("Start");
setTimeout(() => {
console.log("Timer completed");
}, 2000);
console.log("End");
Output:
Start
End
Timer completed
What happened?
JavaScript prints
Start.JavaScript encounters
setTimeout().The browser registers the timer.
JavaScript continues executing the remaining synchronous code.
Endis printed.When the timer becomes eligible to run, its callback is queued as a task.
When the runtime can process that task, the callback executes.
Notice that setTimeout() does not pause JavaScript execution.
It schedules a callback for later.
An Important Point About setTimeout(0)
Consider:
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 0);
console.log("End");
Output:
Start
End
Timer
Why?
Because a zero-millisecond delay does not mean immediate execution.
It means the timer callback can become eligible as soon as the timer rules allow. It still has to wait until the current JavaScript execution finishes and the runtime can process the queued task.
Also, the actual delay may be longer because of browser scheduling, timer throttling, and other work.
5. Understanding the Two Important Queues
Now we reach the heart of the Event Loop.
JavaScript uses different scheduling mechanisms for asynchronous callbacks.
For our browser-focused explanation, the two important categories are:
Task Queue (often informally called the Macrotask Queue).
Microtask Queue.
Let's understand why both exist.
A. Task Queue (Macrotask Queue)
A task represents a unit of work scheduled by the browser.
Common examples include:
setTimeout()callbacks.setInterval()callbacks.User interaction callbacks, such as click handlers.
Some browser event callbacks.
Certain other scheduled browser operations.
For example:
console.log("Start");
setTimeout(() => {
console.log("Timer callback");
}, 0);
console.log("End");
Output:
Start
End
Timer callback
The timer callback is scheduled as a task.
Once the current script finishes, the runtime can process the queued task.
B. Microtask Queue
Now consider Promises.
console.log("Start");
Promise.resolve().then(() => {
console.log("Promise callback");
});
console.log("End");
Output:
Start
End
Promise callback
Why does the Promise callback run after synchronous code?
Because .then() callbacks are scheduled as microtasks.
Microtasks are used for work that needs to run at the next microtask checkpoint, before the runtime moves on to another task.
Common sources include:
Promise
.then()callbacks.Promise
.catch()callbacks.Promise
.finally()callbacks.queueMicrotask().MutationObservercallbacks in browsers.
Let's compare the two queues.
Microtask Queue | Task Queue |
|---|---|
Promise reactions |
|
|
|
| Click event callbacks |
Processed at microtask checkpoints | Processed through task scheduling |
Remember: "Macrotask" is a common teaching term. The browser platform generally uses the term task and has multiple task sources rather than one simple universal macrotask queue.
6. How Does the Event Loop Coordinate Everything?
We now understand:
Call Stack: Executes JavaScript.
Web APIs: Handle browser-provided asynchronous operations.
Task Queue: Holds scheduled tasks.
Microtask Queue: Holds scheduled microtasks.
But who coordinates them?
That's where the Event Loop comes in.
At a simplified level, the browser's execution cycle looks like this:
Execute a task, such as the initial script or an event callback.
When the JavaScript execution finishes, perform a microtask checkpoint.
Process microtasks until the microtask queue is empty.
The browser may perform rendering work when appropriate.
Select another eligible task and repeat.
The important part is that the runtime doesn't simply execute one task, then one microtask, then one task.
It drains the microtask queue completely at the relevant checkpoint.
And if a microtask schedules another microtask, that new microtask is also processed before the checkpoint finishes.
Let's understand this through an example.
console.log("Start");
setTimeout(() => {
console.log("Task");
}, 0);
Promise.resolve().then(() => {
console.log("Microtask");
});
console.log("End");
Output:
Start
End
Microtask
Task
Why?
Startexecutes synchronously.The timer callback is scheduled as a task.
The Promise callback is scheduled as a microtask.
Endexecutes synchronously.The current script finishes.
The microtask checkpoint runs the Promise callback.
The runtime can then process the timer task.

7. Microtasks Have Priority at the Microtask Checkpoint
Let's make this more interesting.
What happens when a microtask schedules another microtask?
console.log("Start");
Promise.resolve().then(() => {
console.log("Microtask 1");
queueMicrotask(() => {
console.log("Microtask 2");
});
});
Promise.resolve().then(() => {
console.log("Microtask 3");
});
setTimeout(() => {
console.log("Task");
}, 0);
console.log("End");
Output:
Start
End
Microtask 1
Microtask 3
Microtask 2
Task
Let's understand the order.
Initially, the microtask queue contains:
Microtask 1
Microtask 3
The first microtask executes and schedules another microtask.
The queue now looks like:
Microtask 3
Microtask 2
The runtime processes Microtask 3, followed by Microtask 2.
Only after the microtask queue becomes empty can the next task be processed.
This is why microtasks are drained completely rather than processing only one microtask per task.
8. Promise Chaining and Microtask Execution
Let's connect the Event Loop with the Promise chaining concepts we studied earlier.
Consider:
console.log("Start");
Promise.resolve()
.then(() => {
console.log("A");
})
.then(() => {
console.log("B");
})
.then(() => {
console.log("C");
});
console.log("End");
Output:
Start
End
A
B
C
Each .then() creates another Promise and registers a reaction that runs when the preceding Promise settles.
The callbacks execute as microtasks.
When one callback completes successfully, it settles the next Promise, allowing the next reaction to be scheduled.
This is why Promise chains execute asynchronously, even when the original Promise is already fulfilled.
A More Interesting Example
console.log("Start");
Promise.resolve().then(() => {
console.log("A");
Promise.resolve().then(() => {
console.log("C");
});
});
Promise.resolve().then(() => {
console.log("B");
});
console.log("End");
Output:
Start
End
A
B
C
Initially, the microtask queue contains:
A
B
When A executes, it schedules C.
Now the queue becomes:
B
C
Therefore, B executes before C.
This is an important interview concept: a microtask scheduled during another microtask is added to the queue and runs after the microtasks already waiting ahead of it.
9. Browser Rendering and the Event Loop
So far, we have discussed JavaScript execution and asynchronous callbacks.
But there is one more important part of browser behavior: rendering.
Imagine that JavaScript is continuously executing code.
When does the browser get time to update the screen?
The browser needs opportunities to perform work such as:
Recalculating styles.
Performing layout.
Painting visual changes.
Compositing layers.
These activities are part of the browser's rendering pipeline.
The browser doesn't necessarily render after every task.
Instead, it performs rendering work when appropriate, depending on the event loop, rendering opportunities, and the display's refresh cycle.
Understanding requestAnimationFrame()
The browser provides requestAnimationFrame() for scheduling callbacks that should run before the next repaint.
Example:
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 0);
requestAnimationFrame(() => {
console.log("Animation Frame");
});
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
The guaranteed ordering for the synchronous statements and Promise callback is:
Start
End
Promise
The relative position of the timer and animation-frame callback is not guaranteed by this example alone.
It depends on browser scheduling and rendering opportunities.
This is why we should not teach a universal rule that says requestAnimationFrame() always executes after a timer or always before it.
Why Does requestAnimationFrame() Matter?
Suppose we want to animate an element.
Instead of using arbitrary timers to repeatedly update its position, we can use requestAnimationFrame().
const box = document.querySelector(".box");
let position = 0;
function animate() {
position += 2;
box.style.transform = `translateX(${position}px)`;
if (position < 300) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
The browser schedules the callback around its rendering cycle.
This makes it useful for smooth animations.
A display refreshing at 60 Hz has approximately 16.67 milliseconds per frame. A 120 Hz display has approximately 8.33 milliseconds per frame.
These are frame intervals, not guaranteed execution budgets. JavaScript, style calculation, layout, painting, and other work all compete for time.
10. Microtask Starvation: When the Queue Never Becomes Empty
We know that the runtime drains the microtask queue before moving on to another task.
But what happens if a microtask continuously schedules another microtask?
Consider:
function starve() {
queueMicrotask(starve);
}
starve();
This function continuously schedules itself as a new microtask.
The microtask queue never becomes empty.
As a result, the runtime cannot reach the next task in the normal way.
This can prevent:
Timer callbacks from running.
User interaction callbacks from running.
The browser from getting an opportunity to render.
Other queued work from progressing.
This problem is called microtask starvation.
How Can We Avoid It?
If we have a long-running process, we should divide the work into smaller pieces.
For example:
function processChunk() {
// Process a small amount of work.
setTimeout(() => {
processChunk();
}, 0);
}
processChunk();
This allows the runtime to return to task scheduling between chunks.
For supported environments, scheduler.yield() can also help cooperative scheduling by allowing work to yield and resume later.
The broader lesson is:
Asynchronous code isn't automatically non-blocking or efficient. We still need to consider how much work we schedule and how long each callback runs.
11. Understanding Fetch and Promises in the Event Loop
Let's combine everything we've learned.
Consider this example:
console.log("Start");
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => {
console.log("Fetch completed:", data[0]);
})
.catch((error) => {
console.error("Fetch error:", error);
});
Promise.resolve().then(() => {
console.log("Promise resolved");
});
console.log("End");
What happens?
Startis printed.fetch()initiates a network request through the browser runtime.JavaScript continues executing without waiting for the network response.
The Promise callback is scheduled as a microtask.
Endis printed.The current script finishes.
The Promise callback runs and prints
Promise resolved.Later, when the network operation completes, the fetch Promise settles and its reaction becomes eligible to run.
The response body is read through
response.json(), which also returns a Promise.When that Promise fulfills, the next
.then()callback runs.
The important thing to understand is that the network response does not have a fixed position relative to every other asynchronous operation.
Its timing depends on the actual network and browser scheduling.
Also, remember that fetch() generally fulfills for HTTP error responses such as 404 or 500. Check response.ok if you want to treat those responses as errors.
12. Event Loop Interview Questions
Question 1: What is the Event Loop?
Answer:
The Event Loop is a mechanism provided by the JavaScript runtime that coordinates the execution of JavaScript with scheduled asynchronous work.
It allows JavaScript to continue executing synchronous code while operations such as timers, network requests, and browser events are handled by the surrounding runtime.
It coordinates tasks, microtasks, and execution opportunities so that asynchronous callbacks can run when the Call Stack is available.
Question 2: Why do we need the Event Loop?
Answer:
JavaScript executes code on a single main Call Stack in the browser.
Without asynchronous scheduling, long-running operations would prevent JavaScript from processing other work.
The Event Loop allows the runtime to schedule callbacks after asynchronous operations become ready, instead of forcing JavaScript to wait synchronously for every operation.
This helps maintain a responsive application.
Question 3: What is the output?
blockMainThread();
console.log("Start");
function blockMainThread() {
const start = Date.now();
while (Date.now() - start < 3000) {}
console.log("Running...");
}
console.log("End");
Output:
Running...
Start
End
Explanation:
blockMainThread() executes synchronously and blocks the main thread for approximately three seconds.
Only after the function finishes does JavaScript execute the remaining statements.
This demonstrates why long-running synchronous operations block JavaScript execution.
Question 4: What is the output?
setTimeout(() => {
console.log("a");
}, 1000);
setTimeout(() => {
console.log("b");
}, 500);
setTimeout(() => {
console.log("c");
}, 0);
function d() {
console.log("d Runs");
}
d();
Output:
d Runs
c
b
a
Explanation:
d()is synchronous, so it runs first.The timer with a zero-millisecond delay becomes eligible before the longer timers.
The 500ms timer becomes eligible before the 1000ms timer.
The actual callbacks can run later than their requested delays, but assuming normal scheduling and no unusual blocking, this is the expected order.
Question 5: What's the output? var vs let inside a loop
Example A: Using var
function example() {
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
}
example();
Output:
3
3
3
Explanation:
var is function-scoped, not block-scoped.
All three callbacks refer to the same variable i.
By the time the callbacks execute, the loop has finished and i has become 3.
Example B: Using let
function example() {
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
}
example();
Output:
0
1
2
Explanation:
let creates a separate binding for each loop iteration in this kind of for loop.
Each callback therefore remembers the value associated with its own iteration.
The first callback has a zero-millisecond delay, the second approximately one second, and the third approximately two seconds.
Question 6: What's the output?
Promise.resolve()
.then(function a() {
Promise.resolve().then(
setTimeout(function d() {
console.log("d Runs");
}, 0)
);
Promise.resolve().then(function e() {
console.log("e Runs");
});
throw new Error("Error Occurred!");
Promise.resolve().then(function f() {
console.log("f Runs");
});
})
.catch(function b() {
console.log("b Runs");
})
.then(function c() {
console.log("c Runs");
});
Output:
e Runs
b Runs
c Runs
d Runs
Let's understand the execution.
Step 1: The first .then() schedules function a as a microtask.
Step 2: Function a starts executing.
Inside a, this code runs:
Promise.resolve().then(
setTimeout(function d() {
console.log("d Runs");
}, 0)
);
An important detail: JavaScript evaluates the argument to .then() immediately.
Therefore, setTimeout() is called immediately while a is executing. It schedules d as a timer task.
The return value of setTimeout() is passed to .then(), rather than the callback function itself.
Step 3: This code schedules e as another microtask:
Promise.resolve().then(function e() {
console.log("e Runs");
});
Step 4: An error is thrown:
throw new Error("Error Occurred!");
The current Promise returned by function a becomes rejected.
The remaining statement that schedules f is never executed.
Step 5: The microtask queue processes e.
Step 6: The rejection reaches .catch(), which prints b Runs.
Step 7: Since the catch callback completes successfully, the next .then() executes and prints c Runs.
Step 8: The timer task eventually runs and prints d Runs.
This question tests Promise chaining, synchronous argument evaluation, microtask scheduling, error propagation, and timer execution.
Question 7: What's the output?
function pause(millis) {
return new Promise((resolve) => {
setTimeout(() => {
resolve("resolved");
}, millis);
});
}
const start = Date.now();
console.log("Start");
pause(1000).then((res) => {
const end = Date.now();
const secs = (end - start) / 1000;
console.log(res, ":", secs);
});
Expected output:
Start
resolved : approximately 1
Explanation:
Startis printed synchronously.pause(1000)creates a Promise.The Promise executor runs synchronously and registers a timer.
JavaScript continues without waiting for the timer.
After approximately one second or longer, the timer callback executes.
resolve("resolved")fulfills the Promise.The
.then()callback is scheduled as a microtask.The callback prints the result and elapsed time.
The exact elapsed time is not guaranteed to be 1.0 or 1.3 seconds. It depends on timer scheduling and how busy the runtime is.
13. Common Event Loop Mistakes
Mistake | Correct understanding |
|---|---|
| It schedules a callback for a later task |
Promises execute synchronously | Promise executors run synchronously, but Promise reactions run as microtasks |
Every asynchronous operation runs on a background thread | The runtime handles different operations using different mechanisms |
The browser renders after every task | Rendering happens when the browser gets an appropriate opportunity |
One microtask runs per task | The microtask queue is drained at the checkpoint |
JavaScript cannot become blocked | Long synchronous work can block the main thread |
| It is a Node.js API |
14. Quick Revision Cheat Sheet
The simplified browser execution model:
Synchronous JavaScript executes on the Call Stack.
Asynchronous work can be delegated to browser runtime facilities.
Completed asynchronous operations can schedule callbacks.
At a microtask checkpoint, the runtime drains the microtask queue.
The browser may perform rendering work when appropriate.
The runtime selects another eligible task.
Remember these concepts:
Concept | Remember |
|---|---|
Call Stack | Executes synchronous JavaScript |
Web APIs | Browser-provided asynchronous facilities |
Event Loop | Coordinates execution and scheduling |
Task Queue | Holds scheduled tasks |
Microtask Queue | Holds Promise reactions and other microtasks |
| Schedules a timer callback |
| Schedules a Promise reaction as a microtask |
| Explicitly schedules a microtask |
| Schedules work before a browser repaint |
Microtask starvation | Continuous microtasks can prevent other work from progressing |
Most important interview rule:
Synchronous code finishes first. At the microtask checkpoint, all queued microtasks are processed before the runtime moves on to another task.
What's Next?
We have now understood how JavaScript coordinates synchronous execution and asynchronous operations.
We also know why Promises, timers, and browser events don't all execute at the same time.
But there's another important question:
Does JavaScript always behave the same way in the browser and in Node.js?
Not exactly.
Node.js has its own Event Loop implementation, including phases for timers, I/O callbacks, polling, checking, and closing callbacks.
It also provides APIs such as setImmediate() and process.nextTick().
In the next chapter, we'll explore the Node.js Event Loop, understand its phases, and learn how process.nextTick(), Promise microtasks, setTimeout(), and setImmediate() interact.