JavaScript Event Loop & Browser Internals ----> A Deep but Practical Guide for Frontend Engineers
The Core Problem JavaScript Solves
JavaScript runs in the browser and must:
-
Respond to user clicks
-
Fetch data from servers
-
Animate UI
-
Handle timers
-
Update the screen
But…
JavaScript is single-threaded
That means:
-
One call stack
-
One task at a time
-
No true parallel execution
So how does the browser avoid freezing the UI?
π By splitting responsibilities between JavaScript Engine, Browser, and the Event Loop
2. High-Level Browser Architecture
Before the event loop, you must understand where JavaScript actually runs.
Here you can have a look on Browser Architecture Overview
Note:
-
JavaScript does NOT do everything
-
Browser provides async powers via Web APIs
JavaScript Engine & Call Stack (Foundation)
The JavaScript Engine (V8, SpiderMonkey) contains:
-
Memory Heap
-
Call Stack
Call Stack Rules
-
Executes code line by line
-
Uses LIFO (Last In, First Out)
4. What Happens With Async Code?
Let’s introduce a timer.
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 2000);
console.log("End");
Expected output:
Start
End
Timeout
5. Web APIs (Browser Superpowers)
setTimeout is not JavaScriptIt is handled by the browser’s Web APIs
Have a look on Web API Handling
JavaScript:
-
Registers the timer
-
Immediately continues execution
-
Does NOT wait
6. Macrotask (Callback) Queue
When the timer finishes:
-
The callback is placed into the Macrotask Queue
But It cannot execute immediately
Why?
π The call stack must be empty
π Event Loop must allow it
The Event Loop (The Traffic Controller)
The Event Loop constantly checks:
-
Is Call Stack empty?
-
Are Microtasks pending?
-
Can I push the next task?
8. Microtask Queue (High Priority)
Microtasks execute before macrotasks.
Microtasks include:
-
Promise
.then -
Promise
.catch -
async/await -
queueMicrotask
Execution Flow
-
A→ Call Stack -
setTimeout→ Web API -
Promise → Microtask Queue
-
D -
Microtasks executed
-
Macrotask executed
Output:







Comments
Post a Comment