Understanding JavaScript’s Event Loop: A Practical Example
I’ve been diving into JavaScript’s asynchronous behavior and here’s a simple example that shows how synchronous and asynchronous code interact: javascript
const displayMessages = () => {
console.log("Hi");
setTimeout(() => { console.log("1") }, 0);
Promise.resolve().then(() => { console.log("2")});
setTimeout(() => { console.log("3") }, 0);
Promise.resolve().then(() => { console.log("4"); });
displayMessages();
}
Output: Hi 2 4 1 3
Explanation:
1️⃣ console.log("Hi") is executed first (synchronous code).
2️⃣ Promises (then) are part of the microtask queue, which is executed after the current code finishes, but before macrotasks like setTimeout.
3️⃣ setTimeout tasks are added to the macrotask queue, which is executed after the microtasks are completed.
🔑 Macrotasks vs Microtasks:
This demonstrates how JavaScript’s event loop manages both synchronous and asynchronous operations efficiently.
#JavaScript #WebDevelopment #EventLoop #AsynchronousProgramming #Macrotasks #Microtasks