How javascript work
Event Loop in JavaScript Explained Simply 🚀
“JavaScript single-threaded ho vane async kasari handle garcha?”
यो question almost every frontend interview ma sodhincha.
If you are a React.js or Next.js developer, understanding the JavaScript Event Loop is not optional anymore. Especially product-based companies, remote jobs, and senior frontend interviews ma yo topic deeply sodhcha.
Because real-world frontend applications depend heavily on:
- API calls
- User interactions
- Rendering performance
- Animations
- State updates
- Async operations
Ra yes sabai ko core ma cha → Event Loop.
Today we’ll deeply understand Event Loop in simple English + Nepali mixed language — beginner friendly but senior-level depth ma.
Why Event Loop is Important? 🔥
Frontend developer ko daily kaam nai async behavior sanga related huncha.
Example:
- Fetching API
- Button click handling
- Search debounce
- Infinite scroll
- React state updates
- Loading spinner
- Notifications
- Timers
- Animations
If Event Loop ramrari bujhena vane:
❌ UI freeze huncha
❌ Performance issues aaucha
❌ React apps laggy huncha
Senior developers differentiate from juniors mainly because they understand:
- browser internals
- async behavior
- rendering performance
- event loop mechanics
JavaScript Runtime Architecture 🧠
JavaScript runtime ko internal architecture bujhna very important cha.
Simple architecture:
Memory Heap
↓
Call Stack
↓
Web APIs
↓
Task Queues
↓
Event LoopNow let’s understand one by one.
1. JavaScript Engine ⚙️
JavaScript engine is the program that executes JavaScript code.
| Browser | Engine |
| ------- | -------------- |
| Chrome | V8 |
| Firefox | SpiderMonkey |
| Safari | JavaScriptCore |Engine le mainly 2 kaam garcha:
- Code parse garne
- Code execute garne
2. JavaScript is Single-Threaded 🧵
JavaScript ekai time ma only one task execute garna sakcha.
Think like:
👉 Single cashier in a shop.
One customer at a time handle garna sakcha.
That means:
console.log("A");
console.log("B");
console.log("C");
Output:
A
B
CSequential execution huncha.
3. Execution Context 📦
Jaba function execute huncha, JavaScript creates an Execution Context.
It contains:
- Variables
- Function references
- this keyword
- Scope information
function greet() {
console.log("Hello");
}
greet();greet() call huda new execution context create huncha.
4. Call Stack 📚
Call Stack is where function execution happens.
It follows:
LIFO Principle
Last In First Out
Like:
🍽️ Plate stack
Last plate rakheko first niskincha.
Example
function one() {
two();
}
function two() {
three();
}
function three() {
console.log("Hello");
}
one();Step-by-Step Stack Flow
Step 1
Call Stack:
one()
Step 2
Call Stack:
one()
two()
Step 3
Call Stack:
one()
two()
three()
Step 4
console.log() executes.
Then stack remove huna thalcha.
three() removed
two() removed
one() removedStack Overflow 🚨
Infinite recursion le stack overflow huncha.
function test() {
test();
}
test();
Output:
Maximum call stack size exceededBecause function endlessly stack ma push bhairacha.
5. Memory Heap 🧠
Memory heap ma objects and variables store huncha.
const user = {
name: "Sachin"
};Object heap memory ma store huncha.
6. Web APIs / Browser APIs 🌐
JavaScript itself le:
❌ timer handle gardaina
❌ DOM handle gardaina
❌ fetch handle gardaina
Browser provides these APIs.
Examples:
- setTimeout
- DOM Events
- fetch
- geolocation
- console
setTimeout(() => {
console.log("Hello");
}, 2000);Browser le timer manage garcha.
JavaScript engine free huncha next code execute garna.
7. Callback Queue (Task Queue) 📥
Jaba async task complete huncha, callback queue ma jancha.
Examples:
- setTimeout
- setInterval
- click events
8. Microtask Queue ⚡
High-priority queue.
Examples:
- Promise.then()
- Promise.catch()
- queueMicrotask()
- MutationObserver
Microtask queue always executes before callback queue.
9. Event Loop 🔄
Main hero 🔥
Event loop continuously check garcha:
Is Call Stack Empty?If empty:
- Execute ALL microtasks
- Then execute one callback/macrotask
Simple Event Loop Diagram
Call Stack Empty?
↓
Execute Microtasks
↓
Execute Callback Queue
↓
Repeat ForeverHow Async Code Works Internally 🔥
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 2000);
console.log("End");Internal Flow
Step 1
console.log("Start")
Output:
Start
Step 2
setTimeout goes to browser Web API.
Timer starts.
Step 3
console.log("End")
Output:
End
Step 4
After 2 sec:
callback goes to callback queue.
Step 5
Event loop checks:
Call stack empty?
YES
Then callback executes.
Output:
TimerMicrotask Queue vs Callback Queue ⚔️
This is MOST IMPORTANT interview topic.
Priority Order
1. Call Stack
2. Microtask Queue
3. Callback QueueExamples of Microtasks
Promise.resolve().then(() => {});
queueMicrotask(() => {});Examples of Callback Queue
setTimeout(() => {});
setInterval(() => {});
button.addEventListener("click", fn);Why Microtasks Execute First? 🤔
Because browser wants promise-based logic to complete ASAP before rendering next task.
That’s why:
Promise.resolve().then(() => {
console.log("Promise");
});
setTimeout(() => {
console.log("Timeout");
}, 0);
Output:
Promise
TimeoutEvent Loop Starvation ⚠️
Too many microtasks can block callback queue.
function spam() {
Promise.resolve().then(spam);
}
spam();This continuously fills microtask queue.
Result:
❌ UI freeze
❌ Timers never execute
Main Example Deep Explanation 🔥
console.log("Start");
setTimeout(() => {
console.log("setTimeout Callback");
}, 0);
Promise.resolve().then(() => {
console.log("Promise Resolved");
});
console.log("End");Step-by-Step Execution
Step 1
console.log("Start");
Output:
Start
Step 2
setTimeout(...)
Timer goes to Web API.
Browser handles timer separately.
Step 3
Promise.resolve().then(...)
Promise callback goes to:
Microtask Queue
Step 4
console.log("End");
Output:
EndCurrent Situation
Call Stack → Empty
Microtask Queue:
- Promise callback
Callback Queue:
- setTimeout callbackEvent Loop Decision
Event loop first checks:
Microtask QueuePromise callback executes FIRST.
Output:
Promise ResolvedThen Callback Queue
Finally:
setTimeout CallbackFinal Output
Start
End
Promise Resolved
setTimeout CallbackImportant Interview Trap 🚨
Many beginners think:
setTimeout(fn, 0)means immediate execution.
❌ Wrong.
It means:
“Execute after current stack + microtasks complete.”
Visual Flow Diagram 🧠
Main Thread
↓
console.log("Start")
setTimeout → Web API
Promise.then → Microtask Queue
console.log("End")
Call Stack Empty
↓
Run Microtasks
↓
Run Callback Queueasync/await Internally Explained 🔥
Many developers use async/await but internally kasari kaam garcha थाहा hudaina.
async Function
async function test() {
return 10;
}Actually returns:
Promise.resolve(10)await Behavior
async function run() {
console.log("A");
await Promise.resolve();
console.log("B");
}
run();
console.log("C");
Output
A
C
BWhy?
await pauses function execution.
Remaining code goes to:
Microtask QueueInternal Working
run()
↓
console.log("A")
await pauses
↓
remaining code queued as microtask
console.log("C")
microtask executes
↓
console.log("B")Common Event Loop Problems 🚨
- Blocking Main Thread
while(true) {
console.log("Blocking");
}Result:
❌ Browser freeze
❌ UI unresponsive
❌ React render stop
Why?
Call stack never becomes empty.
Event loop cannot process other tasks.
Solution ✅
- Use Web Workers
- Break tasks
- Use async operations
2. Delayed setTimeout
setTimeout(() => {
console.log("Timer");
}, 1000);
for(let i = 0; i < 1e9; i++) {}Timer delayed huncha because stack busy cha.
Get Englishjha’s stories in your inbox
Join Medium for free to get updates from this writer.
Output
TimerBut NOT exactly after 1 second.
Important Concept
setTimeout minimum delay ho.
Guaranteed exact timing hoina.
3. Callback Hell 😭
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 1000);
}, 1000);
}, 1000);Looks ugly 😅
Real-World API Example
loginUser(user, () => {
getProfile(() => {
getPosts(() => {
getComments(() => {
});
});
});
});Hard to:
- debug
- maintain
- scale
Promises Solve This ✅
loginUser()
.then(getProfile)
.then(getPosts)
.then(getComments);async/await Better Solution ✅
async function loadData() {
await loginUser();
await getProfile();
await getPosts();
await getComments();
}Cleaner and readable.
Browser vs Node.js Event Loop ⚔️
Many interviews ask this.
Browser Event Loop
Simpler architecture.
Main focus:
- Rendering
- DOM
- User events
Node.js Event Loop
Node.js has phases.
Node.js Phases
1. Timers
2. Pending Callbacks
3. Poll
4. Check
5. Close CallbacksTimers Phase
setTimeout
setIntervalPoll Phase
Handles:
- I/O operations
- File system
- Network requests
process.nextTick vs Promise 🚨
Very common interview trap.
process.nextTick
↓
Promise microtasks
↓
macrotaskssetImmediate vs setTimeout
setImmediate(() => {
console.log("Immediate");
});
setTimeout(() => {
console.log("Timeout");
}, 0);Execution order may vary depending on phase.
React + Event Loop Relation ⚛️
This is SUPER IMPORTANT for frontend engineers.
React State Updates
setCount(count + 1);React batches updates asynchronously.
Event loop helps coordinate:
- rendering
- reconciliation
- DOM updates
useEffect Timing
useEffect runs after paint/render cycle.
Event loop + browser rendering pipeline deeply involved cha.
Blocking Code in React ❌
function heavyTask() {
for(let i = 0; i < 1e9; i++) {}
}This blocks:
- rendering
- clicks
- animations
- typing
React app laggy huncha.
React Concurrent Rendering
Modern React internally schedules tasks smartly.
Uses concepts similar to:
- task prioritization
- yielding
- scheduling
Real-World Examples 🌍
API Fetching
fetch("/api/users")
.then(res => res.json())
.then(data => {
console.log(data);
});Browser handles network async.
UI freeze hudaina.
Search Debounce
setTimeout(() => {
search(query);
}, 500);Prevents unnecessary API calls.
Infinite Scroll
Scroll events queued asynchronously.
Smooth experience maintain huncha.
Loading Spinner
Without async behavior:
❌ spinner visible hudaina
Because main thread blocked huncha.
Animations
Smooth animations need free main thread.
Heavy sync code = dropped frames.
Performance Optimization Tips 🚀
- Break Heavy Tasks
❌ Bad
for(let i = 0; i < 1e9; i++) {}✅ Better
setTimeout(processChunk, 0);2. Use requestAnimationFrame
Better for animations.
requestAnimationFrame(() => {
animate();
});3. Use Web Workers
Heavy calculations separate thread ma run gara.
Main UI responsive huncha.
4. Debouncing
Search optimization.
5. Throttling
Scroll and resize optimization.
6. Avoid Too Many Microtasks
Infinite promise chaining dangerous huncha.
Common Interview Questions 🎯
Q1. Why JavaScript Single-Threaded?
Because simplicity + browser safety.
Avoid race conditions in DOM manipulation.
Q2. Synchronous vs Asynchronous?
| Synchronous | Asynchronous |
| -------------------- | ---------------------- |
| One-by-one execution | Non-blocking execution |
| Blocking | Efficient |
| Simple | Faster UX |Q3. Macrotask vs Microtask?
| Macrotask | Microtask |
| -------------- | --------------- |
| setTimeout | Promise |
| Lower priority | Higher priority |
| Executes later | Executes first |Q4. Why Promise Higher Priority?
To ensure promise chains complete before next rendering/task cycle.
Q5. How setTimeout Works Internally?
- Goes to Web API
- Timer starts
- Callback queue ma jancha
- Event loop waits stack empty
- Executes callback
Q6. Why setTimeout(0) Delayed?
Because:
- current stack complete hunu parcha
- microtasks execute hunu parcha
⚠️ Common Mistakes
- Thinking setTimeout(0) is immediate
- Ignoring microtask queue
- Blocking main thread
- Using too many nested callbacks
- Heavy sync loops in React
💡 Senior Developer Tips
- Think about rendering performance always
- Main thread free rakha
- Prefer async APIs
- Use Web Workers for CPU-heavy work
- Understand browser scheduling deeply
🚀 Interview Shortcuts
Remember this order:
Call Stack
↓
Microtasks
↓
Macrotasks🔥 Important Interview Trap
Question:
Promise.resolve().then(() => console.log(1));
setTimeout(() => console.log(2), 0);
console.log(3);
Correct Answer
3
1
2
Because:
sync first
microtask second
macrotask lastAnother Interview Example 🔥
async function test() {
console.log(1);
await Promise.resolve();
console.log(2);
}
test();
console.log(3);
Output
1
3
210 Rapid-Fire Event Loop Interview Q&A ⚡
- What is Event Loop?
Mechanism that coordinates async tasks in JavaScript.
2. Is JavaScript Multi-threaded?
No. Single-threaded language.
3. What queue has highest priority?
Microtask queue.
4. Examples of microtasks?
- Promise.then
- queueMicrotask
- MutationObserver
5. Examples of macrotasks?
- setTimeout
- setInterval
- DOM events
6. What blocks Event Loop?
Heavy synchronous tasks.
7. Why UI freezes?
Main thread blocked.
8. Does setTimeout guarantee timing?
No. Only minimum delay.
9. Why async/await cleaner?
Avoids callback hell.
10. Why Event Loop important in React?
Impacts rendering, responsiveness, batching, and performance.
Final Summary 🧠
Event Loop is the heart of asynchronous JavaScript.
Without it:
❌ APIs would block UI
❌ React apps freeze hunthyo
❌ Browser unusable hunthyo
Understanding Event Loop helps you:
✅ Write performant frontend apps
✅ Debug async issues
✅ Optimize React rendering
✅ Crack frontend interviews
✅ Become senior-level engineer
Key Takeaways 🔥
Remember forever:
JavaScript = Single Threaded
Async behavior = Browser APIs + Event Loop
Promise > setTimeout
Microtasks > Macrotasks
Heavy sync code = UI freezeSenior Developer Insight 💡
Most developers learn:
async/awaitBut senior engineers understand:
- WHAT happens internally
- WHEN tasks execute
- WHY rendering blocks
- HOW browser scheduling works
That difference makes you interview-ready for:
- Product companies
- Senior frontend roles
- High-performance React apps
- Modern Next.js architecture
Final Conclusion 🚀
If you deeply understand:
- Call Stack
- Web APIs
- Microtask Queue
- Callback Queue
- Event Loop
Then JavaScript async behavior suddenly becomes crystal clear.
And once Event Loop clicks in your brain…
React performance, async debugging, browser rendering, Promise behavior — sabai easy feel huna thalcha 🔥





