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 (4)
it's answer is B
Yes , @john12 , it's correct.
B. 1οΈβ£ Hello, 4οΈβ£ Goodbye, 3οΈβ£ Promise, 2οΈβ£ Timeout
Thanks
@fandyvn , yes it's correct.