Understanding JavaScript’s Event Loop: A Practical Example
Talat Hussain
Reactjs | Nodejs | Expressjs | Nestjs| Socketio | Gsap | Three.js| As a web developer, my goal is to create a customized, beautiful website that meets the client's needs and reflects their brand identity
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