JavaScript Microtasks vs Macrotasks Explained

🚀 Day 84 of My #100DaysOfCode Challenge Today I explored an interesting concept in JavaScript — Microtasks vs Macrotasks. JavaScript is single-threaded, but it can still handle asynchronous operations efficiently using the Event Loop. Behind the scenes, tasks are organized into different queues. 1️⃣ Macrotasks Macrotasks include operations like: - "setTimeout" - "setInterval" - DOM events - I/O operations These tasks go into the Macrotask Queue and are executed after the call stack is empty. 2️⃣ Microtasks Microtasks include: - "Promise.then()" - "Promise.catch()" - "MutationObserver" Microtasks have higher priority and run before macrotasks, even if they were scheduled later. Example console.log("Start"); setTimeout(() => { console.log("Macrotask"); }, 0); Promise.resolve().then(() => { console.log("Microtask"); }); console.log("End"); Output Start End Microtask Macrotask Even though "setTimeout" runs with "0ms", the Promise (Microtask) executes first because microtasks are processed before macrotasks. Understanding these small details helps developers debug asynchronous behavior and write more predictable code. Every day I’m discovering how deep and fascinating JavaScript really is. 💻✨ #Day84 #100DaysOfCode #JavaScript #EventLoop #WebDevelopment #LearningInPublic

  • graphical user interface

To view or add a comment, sign in

Explore content categories