Hey there, JavaScript enthusiast! 👋
Are you ready to unravel the magic behind event loops? It's one of the most exciting (and misunderstood) concepts in JavaScript. In this blog, we’ll skip the heavy theory and dive into hands-on examples to make sure you really get it. 🌟
What Is an Event Loop? 🤔
Simply put, the event loop is how JavaScript manages multiple tasks — like executing code, waiting for API responses, and handling user interactions. It's like a busy host at a party 🎉, making sure everyone (tasks) gets attention in the right order.
JavaScript is single-threaded, meaning it can handle only one task at a time in its main thread. But with the event loop, it creates an illusion of multitasking! 🤯
🧑💻 Let’s Code It!
1️⃣ Synchronous Code 🕒
console.log("1️⃣ Start cooking 🍳");
console.log("2️⃣ Eat breakfast 🍴");
console.log("3️⃣ Wash dishes 🧼");
Output:
1️⃣ Start cooking 🍳
2️⃣ Eat breakfast 🍴
3️⃣ Wash dishes 🧼
📝 Explanation: These tasks happen one after the other (synchronous execution).
2️⃣ Adding Asynchronous Tasks with setTimeout
⏱️
console.log("1️⃣ Start cooking 🍳");
setTimeout(() => {
console.log("2️⃣ Eat breakfast 🍴 (after 3 seconds)");
}, 3000);
console.log("3️⃣ Wash dishes 🧼");
Output:
1️⃣ Start cooking 🍳
3️⃣ Wash dishes 🧼
2️⃣ Eat breakfast 🍴 (after 3 seconds)
📝 Explanation:
- The
setTimeout
task is sent to the Web APIs (not part of the main thread). - Once the timer ends, it’s placed in the Callback Queue, waiting for the main thread to be free.
- The event loop ensures the callback gets executed after synchronous tasks.
3️⃣ Microtasks vs. Macrotasks 🛠️
The event loop prioritizes microtasks (like Promise
callbacks) over macrotasks (like setTimeout
). Let’s see this in action:
console.log("1️⃣ Start 🍳");
setTimeout(() => {
console.log("2️⃣ Macrotask: Timeout ⏳");
}, 0);
Promise.resolve().then(() => {
console.log("3️⃣ Microtask: Promise ✅");
});
console.log("4️⃣ End 🚀");
Output:
1️⃣ Start 🍳
4️⃣ End 🚀
3️⃣ Microtask: Promise ✅
2️⃣ Macrotask: Timeout ⏳
📝 Explanation:
- The Promise callback (microtask) runs before the
setTimeout
callback (macrotask), even thoughsetTimeout
has a delay of0ms
.
4️⃣ Handling Heavy Tasks ⚡
Ever seen a page freeze while running a heavy task? Let's fix that with asynchronous code!
Bad Example (Blocking the Event Loop) 🚫
console.log("1️⃣ Start 🏁");
for (let i = 0; i < 1e9; i++) {} // Simulating heavy task
console.log("2️⃣ End 🛑");
Better Example (Using setTimeout
for Chunking) ✅
console.log("1️⃣ Start 🏁");
let count = 0;
function heavyTask() {
if (count < 1e6) {
count++;
if (count % 100000 === 0) console.log(`Processed ${count} items 🔄`);
setTimeout(heavyTask, 0); // Let the event loop breathe!
} else {
console.log("2️⃣ Task Complete ✅");
}
}
heavyTask();
🧠 Quick Recap
1️⃣ JavaScript runs synchronous code first.
2️⃣ Asynchronous tasks (like setTimeout
) are handled by the event loop.
3️⃣ Microtasks (Promises) take priority over macrotasks (setTimeout).
4️⃣ Break heavy tasks into chunks using asynchronous patterns to keep the UI responsive.
🎯 Test Your Knowledge!
Here’s a small quiz for you. Comment your answers below! 👇
console.log("1️⃣ Hello 👋");
setTimeout(() => {
console.log("2️⃣ Timeout ⏳");
}, 0);
Promise.resolve().then(() => {
console.log("3️⃣ Promise ✅");
});
console.log("4️⃣ Goodbye 👋");
What’s the output?
A. 1️⃣ Hello, 2️⃣ Timeout, 3️⃣ Promise, 4️⃣ Goodbye
B. 1️⃣ Hello, 4️⃣ Goodbye, 3️⃣ Promise, 2️⃣ Timeout
C. 1️⃣ Hello, 3️⃣ Promise, 4️⃣ Goodbye, 2️⃣ Timeout
Drop your answer below and let’s see if you’ve mastered the event loop! 💬
🔥 Let’s Keep the Conversation Going
If you found this helpful, share it with your developer friends! Let’s decode JavaScript together! 🌐✨
And hey, don’t forget to follow me for more coding insights! 🚀
Top comments (22)
If I am reading this correctly, currently the function heavyTask() creates a macrotask for every single incrementation. This probably introduces some overhead.
For further optimization, I believe creating batched macrotasks or using web workers might be even better.
I would suggest combining both techniques and create multiple web workers (e.g., 10) and split the work among them.
If you anyone has a way for even better optimization, I would love to hear it.
it's answer is B
Yes , @john12 , it's correct.
B is the correct answer
Well done!
Answer is b
Indeed
B
Yes @moglimanani , it's correct. Do you know the reason ?
B
Absolutely right @anand_gautam_608efaa21e58 . Do you the know the reason of it's correctness ?
B is the right answer.
correct @emybel !!
The answer is B
Absolutely right @shivani_singh_399f24510a6
B
Spot on !
B. 1️⃣ Hello, 4️⃣ Goodbye, 3️⃣ Promise, 2️⃣ Timeout
Thanks
@fandyvn , yes it's correct.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.