JS Event Loop: Macrotasks & Microtasks Explained

Day 70 of me reading random and basic but important dev topicsss...... Today I revisited event loops..... At its core, the JS engine runs an endless loop: Wait for tasks -> Execute them -> Sleep. But how does it prioritize what to execute next? It comes down to two distinct queues: Macrotasks and Microtasks. 1. The Macrotask Queue (Tasks) When an external event occurs, the browser queues a macrotask. Examples include: • Executing a newly loaded <script> • Dispatching user events (e.g., mousemove, click) • Running a setTimeout / setInterval callback Tasks are processed "first come, first served." But here is the critical part: Rendering never happens while a task is executing. If a single macrotask takes too long, the browser can't process user inputs or paint to the DOM, eventually throwing a "Page Unresponsive" error. 2. The Microtask Queue Microtasks come strictly from our code. The most common sources are: • Promise handlers (.then, .catch, .finally) • await operations • Explicitly queued tasks via queueMicrotask(func) The Execution Order (The Golden Rule): 1. Dequeue and run the oldest Macrotask. 2. Execute ALL Microtasks. If a microtask creates another microtask, it gets executed in this same phase! 3. Render DOM changes (if any). 4. Wait for the next Macrotask and repeat. Microtasks run immediately after the current macrotask and before any UI rendering or network event handling. This guarantees that application state remains untouched between microtasks.... Keep Learning!!!!!! #JavaScript #WebDevelopment #SoftwareEngineering #FrontendDev #EventLoop

  • graphical user interface, diagram

To view or add a comment, sign in

Explore content categories