DEV Community

Cover image for πŸš€ Let’s Learn Event Loops in JavaScript! 🎑
Jagroop Singh
Jagroop Singh

Posted on

πŸš€ Let’s Learn Event Loops in JavaScript! 🎑

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 🧼");  
Enter fullscreen mode Exit fullscreen mode

Output:

1️⃣ Start cooking 🍳  
2️⃣ Eat breakfast 🍴  
3️⃣ Wash dishes 🧼  
Enter fullscreen mode Exit fullscreen mode

πŸ“ 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 🧼");  
Enter fullscreen mode Exit fullscreen mode

Output:

1️⃣ Start cooking 🍳  
3️⃣ Wash dishes 🧼  
2️⃣ Eat breakfast 🍴 (after 3 seconds)  
Enter fullscreen mode Exit fullscreen mode

πŸ“ 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 πŸš€");  
Enter fullscreen mode Exit fullscreen mode

Output:

1️⃣ Start 🍳  
4️⃣ End πŸš€  
3️⃣ Microtask: Promise βœ…  
2️⃣ Macrotask: Timeout ⏳  
Enter fullscreen mode Exit fullscreen mode

πŸ“ Explanation:

  • The Promise callback (microtask) runs before the setTimeout callback (macrotask), even though setTimeout has a delay of 0ms.

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 πŸ›‘");  
Enter fullscreen mode Exit fullscreen mode

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();  
Enter fullscreen mode Exit fullscreen mode

🧠 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 πŸ‘‹");  
Enter fullscreen mode Exit fullscreen mode

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 (13)

Collapse
 
emybel profile image
Imane BELAID

B is the right answer.

Collapse
 
jagroop2001 profile image
Jagroop Singh

correct @emybel !!

Collapse
 
moglimanani profile image
manimaran

B

Collapse
 
jagroop2001 profile image
Jagroop Singh

Yes @moglimanani , it's correct. Do you know the reason ?

Collapse
 
john12 profile image
john

it's answer is B

Collapse
 
jagroop2001 profile image
Jagroop Singh

Yes , @john12 , it's correct.

Collapse
 
anand_gautam_608efaa21e58 profile image
Anand Gautam

B

Collapse
 
jagroop2001 profile image
Jagroop Singh

Absolutely right @anand_gautam_608efaa21e58 . Do you the know the reason of it's correctness ?

Collapse
 
fandyvn profile image
Fandy

B. 1️⃣ Hello, 4️⃣ Goodbye, 3️⃣ Promise, 2️⃣ Timeout
Thanks

Collapse
 
jagroop2001 profile image
Jagroop Singh

@fandyvn , yes it's correct.

Collapse
 
shivani_singh_399f24510a6 profile image
Shivani Singh

The answer is B

Collapse
 
jagroop2001 profile image
Jagroop Singh

Absolutely right @shivani_singh_399f24510a6

Collapse
 
muhammad_usama_db59ea3065 profile image
Muhammad Usama

B