JavaScript Event Loop: Microtask vs Macrotask Explained

JavaScript Event Loop (Microtask vs Macrotask) — explanation We often see this code: console.log("start") setTimeout(() => { console.log("timeout") }, 0) Promise.resolve().then(() => { console.log("promise") }) console.log("end") Output: start end promise timeout Why does this happen? Basic: JavaScript is single-threaded That means it runs one thing at a time (Call Stack) But async tasks like setTimeout and Promise go to different queues. There are two types of queues: Microtask Queue (high priority) Promise.then() async/await Macrotask Queue (low priority) setTimeout setInterval DOM events Event Loop rule (very important): First, all synchronous code runs Then, all microtasks run Then, one macrotask runs Then the loop continues Easy way to remember: Sync → Microtask → Macrotask → Repeat Example breakdown: console.log("start") // sync setTimeout(() => { console.log("timeout") // macrotask }, 0) Promise.resolve().then(() => { console.log("promise") // microtask }) console.log("end") // sync Step by step: start → prints end → prints promise → runs next (microtask, higher priority) timeout → runs last (macrotask) Common mistake: Many people think: “setTimeout with 0ms runs immediately” This is wrong It only goes to the queue, it does not run immediately Final takeaway: JavaScript runs synchronous code first Then microtasks (Promise) Then macrotasks (setTimeout) Pro tip: If you understand this concept well, it will help you with: API handling React state updates Debugging async issues

1. There is no event loop in JavaScript. Event Loop is a host environment artifact that exists only there, where you embed JavaScript, because JavaScript is a scripting language. It cannot exist without being embedded somewhere. So when you talk about "Event loop in JS" you probably mean Event Loop of some specific host environment like Browser or Node js. Your host environment can even run js runtime without event loop. 2. JavaScript is not single or multi threaded. Again, it's a scripting language so it needs to be embedded into some host. That host can provide an ability to run js runtime in multiple threads. The question is does JS specification give us anything to work with JS in multiple threads? Yes, it does. We have Atomics and SharedArrayBuffer which allow you to do some stuff it multiple threads.

To view or add a comment, sign in

Explore content categories