🚀 Let’s Learn Event Loops in JavaScript! 🎡
Jagroop Singh

Jagroop Singh @jagroop2001

About: 👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views

Location:
India
Joined:
Apr 5, 2022

🚀 Let’s Learn Event Loops in JavaScript! 🎡

Publish Date: Nov 26 '24
89 26

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! 🚀

Comments 26 total

  • john
    johnNov 26, 2024

    it's answer is B

  • Fandy
    FandyNov 26, 2024

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

  • Imane BELAID
    Imane BELAIDNov 26, 2024

    B is the right answer.

  • Anand Gautam
    Anand GautamNov 26, 2024

    B

  • Shivani Singh
    Shivani SinghNov 26, 2024

    The answer is B

  • manimaran
    manimaranNov 26, 2024

    B

  • Muhammad Usama
    Muhammad UsamaNov 26, 2024

    B

  • Anonymous
    AnonymousNov 27, 2024

    B is the correct answer

  • nidhi sharma
    nidhi sharmaNov 27, 2024

    Answer is b

  • jimzord12
    jimzord12Nov 27, 2024

    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.

    • Kiera Bryant
      Kiera BryantNov 27, 2024

      Great breakdown of JavaScript event loops! As we continue to polish our coding skills, it’s also important to keep our professional profiles sharp. If you’re looking for help with resumes, check out resume writers in Kansas City - resumefolks.com/resume-writing-ser... for expert guidance to highlight your technical expertise effectively.

  • Oks Oksanium
    Oks OksaniumNov 28, 2024

    What does the code after the line "Better Example (Using setTimeout for Chunking)" mean? Is it infinity recursion? Why?

  • Ndeye Fatou Diop
    Ndeye Fatou DiopNov 28, 2024

    Very cool post 😎

  • BobbyleeX
    BobbyleeXNov 28, 2024

    B

  • Sehan Randilu
    Sehan RandiluNov 29, 2024

    Best Programming Codes to Sell
    Get the best programming codes — 5000+ codes to buy or download for free!
    programmingcodesabc2.blogspot.com/

  • Sundaresan Anandan
    Sundaresan AnandanMar 18, 2025

    Very Interesting way of teaching and simple to understand. Answer is 'B'. Also I am not able to understand 'Handling Heavy Tasks', maybe because I am pretty new to JS, next please explain that deeply

Add comment