<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abdullah Abrar on Medium]]></title>
        <description><![CDATA[Stories by Abdullah Abrar on Medium]]></description>
        <link>https://medium.com/@abdullah.abrar_59377?source=rss-9fc3229bff77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cBDo-7aPqQidO07W</url>
            <title>Stories by Abdullah Abrar on Medium</title>
            <link>https://medium.com/@abdullah.abrar_59377?source=rss-9fc3229bff77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:02:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdullah.abrar_59377/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Behind The Scenes: Event Loops In Action]]></title>
            <link>https://medium.com/emumba/behind-the-scenes-event-loops-in-action-0a1222d6a57d?source=rss-9fc3229bff77------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a1222d6a57d</guid>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[event-loop-in-javascript]]></category>
            <dc:creator><![CDATA[Abdullah Abrar]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 13:09:03 GMT</pubDate>
            <atom:updated>2025-07-09T13:09:03.784Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Picture this.</strong><br>You click a button on a website.<br>Instantly, a loader appears, an animation kicks off, and — just seconds later your data shows up like magic.</p><p>But <em>here’s the twist</em>: JavaScript runs on a <strong>single thread</strong>.<br>So how does it multitask like a pro juggler in a circus?<br>How does it <strong>wait for a response</strong>, <strong>animate a button</strong>, <strong>log a message</strong>, and still <strong>keep the UI buttery smooth</strong>?</p><p>Welcome to the <strong>event loop</strong> — the unsung hero of every responsive app you’ve ever built or used.<br> It’s the backstage manager, the traffic cop, the maestro conducting a chaotic orchestra of callbacks, tasks, and promises — all on <strong>one stage</strong>.</p><p>This isn’t just another deep dive.<br>This is a <em>behind-the-scenes tour</em> of JavaScript’s core runtime mechanic — the thing that makes setTimeout, fetch, and async/await even <em>possible</em>.</p><p>In this article, you’ll discover:</p><ul><li>Why JavaScript’s single-threaded nature isn’t a limitation, but a design genius</li><li>How the call stack, task queue, microtasks, and Web APIs work in harmony</li><li>Real-world async examples decoded visually</li><li>Pro tips to write non-blocking, performant code like a pro</li></ul><p>By the end, you won’t just “know” what the event loop is — <br>You’ll <strong>see it</strong>, <strong>feel it</strong>, and <strong>use it</strong> confidently.<br>Let’s lift the curtain. The event loop is about to take the stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-BYpIhggD_lIeFKStG2Tw.png" /></figure><h3>1. Memory Heap</h3><p>Think of this as JavaScript’s <strong>long-term memory</strong>.<br> It’s where <strong>objects</strong>, <strong>variables</strong>, and <strong>functions</strong> live — kind of like shelves in a warehouse.<br> Any data your code creates gets stored here, especially the complex stuff.</p><p><strong>Example:</strong><br> When you write const user = { name: &quot;Mirza&quot; }, this object lives in the memory heap.</p><h3>2. Call Stack</h3><p>The <strong>call stack</strong> is JavaScript’s <strong>to-do list</strong>.<br>It keeps track of what function is currently being executed, and what to do next.<br>It operates in <strong>LIFO</strong> (Last In, First Out) order — meaning the last function called must finish before the one beneath it can continue.</p><p><strong>Example:</strong><br>If function A() calls function B(), B is pushed on top. Once B finishes, it&#39;s popped off, and A resumes.</p><p><strong>Blocking Warning</strong>:<br>If the call stack is busy with a long-running task, everything else (like UI updates) gets frozen. That’s why we use async programming!</p><h3>3. Web APIs (Browser APIs)</h3><p>When you call something like setTimeout, fetch, or interact with the DOM, <strong>those functions are actually handled by the browser</strong>, <em>not</em> JavaScript itself.</p><p>These are <strong>Web APIs</strong>, and they handle things like:</p><ul><li>Timers (setTimeout, setInterval)</li><li>AJAX requests (fetch, XMLHttpRequest)</li><li>DOM events (onclick, keydown)</li><li>Geolocation, local storage, etc.</li></ul><p><strong>The magic?</strong><br>They run <strong>outside the call stack</strong>, in parallel, and push results back when ready.</p><h3>4. Callback Queue (aka Task Queue)</h3><p>Once a Web API finishes its job (like a timer expiring or data coming back from an API), it sends a <strong>callback function</strong> to the <strong>callback queue</strong>.</p><p>Think of this as a <strong>waiting line</strong> for tasks that are <em>ready</em> to be executed but haven’t been processed yet.</p><p>Examples:</p><ul><li>onClick → triggered by a user click</li><li>onLoad → triggered when data loads</li><li>onDone → could be from a setTimeout or an AJAX response</li></ul><h3>6. Microtask Queue</h3><p>This is another waiting line, but with a VIP pass. The microtask queue has a higher priority than the regular callback queue. Callbacks from <strong>Promises</strong> (like .then(), .catch(), .finally()) and other modern APIs like MutationObserver go here. The event loop will <em>always</em> process all tasks in the microtask queue before moving on to the next task in the callback queue.</p><h3>5. The Event Loop (The Real Hero)</h3><p>Now comes the true orchestrator: <strong>The Event Loop</strong>.</p><p>Its job is simple, but critical:</p><p><strong><em>Keep checking</em></strong><em> — if the call stack is empty, and if there’s anything in the callback queue, then move it into the stack and run it.</em></p><p>This loop runs <strong>forever</strong> in your JavaScript runtime — constantly cycling between the stack and the queue.</p><p>🎩 <strong>Fun fact</strong>: Without the event loop, your setTimeout(fn, 0) would <em>never</em> run, even though it seems “immediate” — because the stack must be clear first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Xr4n6zIhlBxqE5vH8r_v1w.png" /></figure><h3>What happens behind the scenes:</h3><ol><li>Here’s what happens behind the scenes:</li><li>console.log(&quot;Start&quot;) is pushed to the call stack, runs immediately, and is popped off.</li><li>setTimeout(...) is pushed to the stack. JavaScript sees it&#39;s a Web API function and hands it off to the browser to manage the 1-second timer. Then setTimeout is popped off the stack.</li><li>console.log(&quot;End&quot;) is pushed to the call stack, runs immediately, and is popped off.</li><li>The call stack is now empty. Meanwhile, the browser’s timer is still counting down.</li><li>After 1 second, the timer finishes, and the browser pushes the callback function () =&gt; console.log(&quot;Inside setTimeout&quot;) into the <strong>callback queue</strong>.</li><li>The <strong>event loop</strong> sees that the call stack is empty and that there’s a task waiting in the callback queue. It pushes the callback onto the stack.</li><li>The callback function runs, logging “Inside setTimeout”, and is then popped off the stack.</li></ol><p><strong>Example#2</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZM4ka8cI-PLGakX1rYs4A.png" /></figure><p><strong>Output</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWB9PMnx1d05Q2GFfX-j8g.png" /></figure><p><strong>Here’s the breakdown:</strong></p><ol><li>&quot;1. Start&quot; is logged.</li><li>setTimeout is handed to the Web API. Its callback is placed in the <strong>Callback Queue</strong> almost instantly (since the delay is 0).</li><li>Promise.resolve().then() is handled. Its callback is placed in the high-priority <strong>Microtask Queue</strong>.</li><li>&quot;2. End&quot; is logged.</li><li>Now the main script is done and the call stack is empty. The Event Loop makes its check.</li><li><strong>It checks the Microtask Queue first.</strong> It finds the promise callback, pushes it to the stack, and runs it. &quot;3. Microtask Queue...&quot; is logged.</li><li>The Event Loop checks the Microtask Queue again. It’s empty.</li><li><strong>Now, it checks the Callback Queue.</strong> It finds the setTimeout callback, pushes it to the stack, and runs it. &quot;4. Callback Queue...&quot; is logged.</li></ol><p>This example proves a critical rule: <strong>microtasks always execute before the next task in the callback queue.</strong> This is why async/await, which is built on Promises, feels so immediate and responsive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlNXzPhKNWPbJrg45kjqRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*HJB6n1WXujI7FhSKZPkLVA.png" /></figure><h4>The Step-by-Step Breakdown:</h4><p><strong>Phase 1: Synchronous Execution</strong></p><ul><li>A: Script start is logged.</li><li>The setTimeout is handed to the Web API. Its callback (F and G) is placed in the <strong>Callback (Macro) Queue</strong>.</li><li>myAsyncFunction() is called.</li><li>C: Async function start is logged synchronously.</li><li>The await is encountered. It pauses the function, and the code after it (E) is scheduled to run in the <strong>Microtask Queue</strong>.</li><li>The Promise.resolve().then() is handled. Its callback (D) is also placed in the <strong>Microtask Queue</strong>.</li><li>B: Script end is logged. The main script is now finished.</li></ul><p><strong>Phase 2: The Microtask Queue</strong></p><ul><li>The Call Stack is now empty. The Event Loop checks the <strong>Microtask Queue</strong> before anything else.</li><li>It finds two items: the promise callback (D) and the continuation of the async function (E). They run in the order they were added.</li><li>D: Promise is logged.</li><li>E: Async function end is logged.</li><li>The Microtask Queue is now empty.</li></ul><p><strong>Phase 3: The Callback (Macrotask) Queue</strong></p><ul><li>The Event Loop now checks the <strong>Callback Queue</strong>. It finds the setTimeout callback.</li><li>The callback is moved to the Call Stack and executed.</li><li>F: setTimeout is logged.</li><li>Oh, but look! Inside this macrotask, we schedule <em>another</em> microtask (G).</li><li>This new microtask (G) is added to the Microtask Queue. The event loop rule states that it must run all available microtasks <em>after</em> the current task (the setTimeout callback) completes and before the <em>next</em> macrotask.</li><li>G: Promise inside setTimeout is logged.</li></ul><p>This example perfectly illustrates the event loop’s strict rules: run the current stack, empty the entire microtask queue, then process one macrotask from the callback queue. Repeat.</p><h3>Conclusion: Embrace the Loop</h3><p>Understanding the event loop is a rite of passage for any serious JavaScript developer. It’s the invisible force that orchestrates the asynchronous magic we rely on to build modern, responsive, and high-performing applications. By grasping the interplay of the call stack, Web APIs, and the different queues — especially the priority of the microtask queue — you gain a deeper appreciation for how your code executes and can write more efficient and predictable asynchronous code.</p><p>So next time you write a setTimeout or a fetch request, you&#39;ll know exactly what&#39;s happening &quot;behind the scenes&quot; as the event loop diligently works its magic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a1222d6a57d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/emumba/behind-the-scenes-event-loops-in-action-0a1222d6a57d">Behind The Scenes: Event Loops In Action</a> was originally published in <a href="https://medium.com/emumba">Emumba</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>