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

Collapse
 
jimzord12 profile image
jimzord12

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.

Collapse
 
john12 profile image
john

it's answer is B

Collapse
 
jagroop2001 profile image
Jagroop Singh

Yes , @john12 , it's correct.

Collapse
 
hng_thc_7942da846939a35 profile image
Hα»“ng Thα»©c

B is the correct answer

Collapse
 
jagroop2001 profile image
Jagroop Singh

Well done!

Collapse
 
nidhi_sharma_3ce9c763fc04 profile image
nidhi sharma

Answer is b

Collapse
 
jagroop2001 profile image
Jagroop Singh

Indeed

Collapse
 
moglimanani profile image
manimaran

B

Collapse
 
jagroop2001 profile image
Jagroop Singh

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

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
 
emybel profile image
Imane BELAID

B is the right answer.

Collapse
 
jagroop2001 profile image
Jagroop Singh

correct @emybel !!

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

Collapse
 
jagroop2001 profile image
Jagroop Singh

Spot on !

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.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.