The independent file on technology, travel & lifeFrom Pakistan, for everywhere
Huzi Blogs.
The ArchiveSectionsSearch

Planning a trip? HTG Travels — flights, visas, hotels & Umrah, handled properly.

WhatsApp +92 317 5054959
Huzi Blogs.

An independent file on technology, travel and life — long-form guides written plainly, from Pakistan, for everywhere.

ShopMeet the Creator

Sections

  • Travel
  • Technology
  • Lifestyle
  • Programming
  • Sports
  • Linux
  • All sections

The Desk

  • The Archive
  • Search the file
  • Disclaimer & Data Privacy Policy
  • A project of huzi.pk

© 2026 blogs.huzi.pk — All rights reserved.

Set in Playfair Display & Inter

    HomeProgrammingStory
    Programming

    The Heartbeat of JS: Understanding the Event Loop (2026)

    H

    By Huzi

    File #450 · 4 min read

    JavaScript is single-threaded, yet it fetches data, runs timers, and streams chat responses without freezing the page. Every junior developer is told this; few are told how. The answer is the event loop, and once you can see it, half of async JavaScript stops being superstition.

    The quick answer: Your code runs on one call stack; everything slow — timers, network, events — is outsourced to Web APIs, and finished callbacks re-enter through queues. Promises use a separate microtask queue that always drains before the next timer, and blocking the stack freezes everything. That is the whole machine.

    Where your code actually lives

    Three places, constantly handing work to each other:

    Place What it does Example
    The call stack Runs synchronous code, one frame at a time, last in first out — while it is busy, nothing else on the main thread happens Every function you call
    The Web APIs The browser's back kitchen, where timing and networking are taken off your hands setTimeout, fetch, DOM events
    The callback queue The pick-up counter where finished callbacks wait their turn setTimeout(fn, 0) after the stack empties
    The microtask queue Where promises wait — and always get called before the next timer .then callbacks, await continuations, queueMicrotask
    libuv in Node.js Runs the same design, its loop polling for I/O and running ready callbacks on the main thread Server-side async

    The loop itself asks two questions forever: is the stack empty, and is a callback waiting? Only when both answers align does a task get pushed on. That is why setTimeout(fn, 0) never runs immediately — zero milliseconds is a queue position, not a starting gun.

    Microtasks jump the queue

    Promises do not wait in the regular line. .then callbacks, await continuations, and queueMicrotask go to the microtask queue, and the loop drains it completely after every macrotask — before the next timer, before rendering. Predict the output before you run it:

    console.log("1");
    setTimeout(() => console.log("2"), 0);
    Promise.resolve().then(() => console.log("3"));
    console.log("4");
    // Output: 1, 4, 3, 2
    

    Pro tip: Respect the queue — an infinite microtask loop starves rendering, timers and input, and the tab hangs.

    Do not block the loop

    A long synchronous loop is the classic footgun: the page cannot paint, clicks go dead, and the browser offers to close the tab. Break the work up and hand control back periodically. scheduler.yield(), the successor to scheduler.postTask, is now baseline in Chrome, Edge, and Safari:

    async function processItems(items) {
      for (const item of items) {
        doExpensiveWork(item);
        await scheduler.yield(); // let the browser paint and take input
      }
    }
    

    For genuinely heavy computation, leave the main thread altogether — Web Workers run real parallel threads and message results back home:

    const worker = new Worker("./heavy.js", { type: "module" });
    worker.postMessage({ data: largeArray });
    worker.onmessage = (e) => updateUI(e.data);
    

    And for token streams from LLM endpoints or large file reads, the async iterator rides the same microtask machinery with cleaner syntax:

    const response = await fetch("/api/chat");
    for await (const chunk of response.body) {
      appendToUi(chunk);
    }
    

    A good travel desk schedules the way this section preaches: fare searches, visa queues and rebooking calls run in the background while the main thread — you — stays free. HTG Travels has run that loop from Sialkot for years, and nothing blocks.

    The coffee-shop version

    You order, take a buzzer, and sit down; the cashier serves the next customer; your name is called only when the counter is free; and the VIP line of pending promises always goes first.

    The loop's philosophy — waiting without freezing — is embodied by Palestine's students, who keep their place in the queue through connectivity that arrives in fragments.

    When an airline cancels a flight at 2 AM, our desk at HTG Travels runs a very human loop: check the queue, rebook, retry, confirm — until a family from Sialkot or Lahore is holding a real ticket rather than a promise. The waiting is our job, so it stops being yours. The working line is +92 317 5054959.

    Presented by

    HTG Travels — Plan the Trip, Skip the Runaround

    Flights, visas, Umrah packages and Hunza–Skardu tours, handled end to end from our licensed Sialkot desk. Real fares, hotel names in writing, and a human who answers — before you pay a rupee.

    Flights & rebooking Visa files Umrah 2026–27 Northern tours
    Visit huzi.pkWhatsApp +92 317 5054959

    Sialkot, Pakistan · Licensed agency · Fast quotes on WhatsApp


    You Might Also Like

    2-Piece Scroll Embroidered Lawn Suit | Heavy Daman & Trouser Patches (2025)

    2-Piece Scroll Embroidered Lawn Suit | Heavy Daman & Trouser Patches (2025)

    PKR 3400

    Luxury Heavy Embroidered Cotton Suit 3-Pc | Embroidered Bamber Chiffon Dupatta (2025)

    Luxury Heavy Embroidered Cotton Suit 3-Pc | Embroidered Bamber Chiffon Dupatta (2025)

    PKR 4700

    All-Over Digital Print Swiss Lawn Suit 3-Pc | Digital Printed Silk Dupatta (2025)

    All-Over Digital Print Swiss Lawn Suit 3-Pc | Digital Printed Silk Dupatta (2025)

    PKR 3800

    Luxury Heavy Embroidered Fancy Lawn 3-Pc Suit | 4-Side Organza Dupatta & Tassels

    Luxury Heavy Embroidered Fancy Lawn 3-Pc Suit | 4-Side Organza Dupatta & Tassels

    PKR 6650

    Cultural Heavy Embroidered Lawn Suit 3-Pc | Embroidered Chiffon Dupatta (2025)

    Cultural Heavy Embroidered Lawn Suit 3-Pc | Embroidered Chiffon Dupatta (2025)

    PKR 4800

    Keep reading

    Related files

    Programming
    English

    Understanding HTML5 and Its Modern Features (2026)

    The living HTML standard in 2026: semantic structure, native video with subtitles, dialog and popover, lazy loading, honest form controls and Web Components — with copy-paste markup.

    By HuziFile #270

    Read
    Programming
    English

    The Variables Revolution: Mastering CSS Custom Properties (2026)

    Custom properties are live DOM values, not compile-time strings: dynamic theming, scoped tokens, JavaScript interop, and animatable typed variables with @property.

    By HuziFile #110

    Read
    Programming
    English

    A Beginner's Guide to React Hooks: Mastering Modern React (2026)

    useState, useEffect, the React 19 form hooks, and the two rules that keep hooks from breaking — each with a runnable snippet.

    By HuziFile #10

    Read
    Programming
    English

    The Connective Tissue: What is an API? (2026)

    APIs explained without the jargon: the restaurant analogy, REST versus GraphQL versus gRPC, webhooks, keys and OAuth, and the design habits that make an interface last.

    By HuziFile #462

    Read
    Programming
    English

    Web Development: Essential Strategies for Modern Websites (2026)

    Frontend and backend split, a tool-by-tool delivery lifecycle, Core Web Vitals budgets, security non-negotiables, and the AI-assisted stack that defines 2026 web work.

    By HuziFile #459

    Read
    Programming
    English

    The Ultimate HTML Reference Guide: Every Tag, Attribute, and Technique (2026)

    A working shelf for 2026 markup — the document skeleton, media tags that protect Core Web Vitals, form input types, and the checks that catch real bugs.

    By HuziFile #419

    Read
    Back to the archive