Author: MangoByteLtd

  • How the JavaScript Event Loop Works, Explained by a Busy Café

    How the JavaScript Event Loop Works, Explained by a Busy Café

    ou’re next in line at a café. The barista starts an espresso, turns to you, and takes your order while the shot pours. Now imagine the same barista counting every coffee bean in the shop by hand. The espresso machine can still finish, and the doorbell can still ring, but nobody at the counter can answer “Could I get that iced?”

    A web page can feel like either café. It can stay responsive through a two-second network request, then freeze during a calculation that takes half a second. The difference is what the page’s main thread is doing when you need its attention. MDN

    The call stack is the barista’s counter

    Say you tap Add iced latte in the café’s ordering app. The function handling your tap calls another function to calculate the price. That function calls a third to look up the oat milk surcharge. JavaScript keeps track of these unfinished calls on the call stack. The most recent call sits on top. It returns the surcharge, the price calculation finishes, and the original tap handler can update your basket. MDN

    It’s one order with several steps. If you tap Checkout halfway through the calculation, the code handling your new tap has to wait. For a little arithmetic, you’ll barely notice. If adding a latte also recalculates the total for every order the café has taken this month, you might tap Checkout twice because the first tap appeared to do nothing. MDN

    Who watches the espresso machine?

    Now the app needs to ask the server which pickup times are available. It starts a network request with fetch(). The browser manages the request, leaving the main thread available for other work. If the ordering function uses await, that function pauses at the point where it needs the answer. Meanwhile, you can still open the menu or change your drink size. MDN

    When the answer arrives, the rest of the function becomes eligible to run. Think of the espresso machine beeping. The drink is ready, but if the barista is counting change, they finish before picking up the cup. In the browser, the event loop coordinates when ready work gets a turn on the main thread. That’s why a server can reply promptly and the page can still take a moment to show the pickup times. MDN

    Which order comes next?

    Here’s a small experiment. Read these four lines and guess which message appears last. Then run them together in your browser console.

    console.log("Barista takes the order");
    setTimeout(() => console.log("Timer rings"), 0);
    Promise.resolve().then(() => console.log("Payment confirmed"));
    console.log("Barista puts down the pen");
    OrderMessageWhy it appears here
    1Barista takes the orderThe first line runs immediately.
    2Barista puts down the penThe script continues after scheduling the two callbacks.
    3Payment confirmedThe promise is already fulfilled, so its callback is waiting in the microtask queue.
    4Timer ringsThe timer callback gets a later turn, after the waiting microtask.

    The timer was registered first and given a delay of zero. So how did it come last? A zero-delay timer asks for a future turn. The promise callback gets a different kind of turn, called a microtask. When the current task finishes, the browser runs waiting microtasks before selecting another task. It drains that queue even if a microtask adds another one. A long chain can therefore keep a customer’s click waiting and delay the next screen update. MDN

    Why “Preparing your report…” sometimes never appears

    Picture the café manager clicking Export sales report. The app changes the button text to Preparing your report…, calculates totals across 80,000 orders, and changes the text again to Download report. All of that happens inside one click handler. On screen, the button seems stuck on Export and then jumps straight to Download. Where did the middle message go?

    The code changed the text twice. The browser only got a chance to paint the result after the calculation finished. This is one reason developers look for long tasks when investigating a frozen interface. In a browser performance trace, that term means a main-thread task lasting longer than 50 milliseconds. A customer experiences it more simply. They tap a button and wonder whether the app heard them. MDN

    For this report, one fix is to process orders in batches and yield between them. Those breaks give the browser a chance to display progress and handle a click on Cancel. For a calculation that takes sustained CPU time, a Web Worker can compute the totals on a separate thread and send the result back. Simply declaring the export function async leaves the calculation on the same thread. A practical way to test the improvement is to start the export and immediately try to cancel it. Does the button respond while the report is still being prepared? web.dev

    Conclusion

    A good barista can take your order while the espresso pours. A responsive page can do the same while a server answers. The trouble starts when one job occupies the counter so long that every small request piles up behind it. When a page feels frozen, ask “What was the main thread doing when I clicked?” The answer can show you where to shorten a calculation, split it into turns, or hand it to a worker so the next customer can be served.

  • When Should a Web Page Be Built? A Practical Guide to SSR, SSG, and CSR

    When Should a Web Page Be Built? A Practical Guide to SSR, SSG, and CSR

    A shopper opens a page for a ceramic mug. The description says it holds 300 ml. The stock counter says there’s one blue mug left. The shopper taps the green swatch and expects the photo to change immediately. All three details share a screen, but each has a different deadline. The mug’s capacity was known before anyone visited. Its availability matters the moment someone wants to buy. The color choice only becomes known when someone taps.

    That’s the decision behind web rendering. A site can prepare HTML ahead of time, assemble it when a request arrives, or let JavaScript build part of the interface in the browser. What makes one approach a good fit depends on what the visitor came to do.

    Static generation does the work before the visit

    With static site generation (SSG), the site turns content and templates into HTML ahead of time. When a shopper opens the mug page, a content delivery network (CDN) can serve a ready-made copy from a nearby location. The browser can start displaying the description as the HTML arrives. A hundred people can read the care instructions without the shop querying its catalog a hundred times. web.dev

    The interesting question is what happens when an editor makes a correction. Suppose the mug was listed as dishwasher-safe and the potter changes the instructions to “hand wash only.” How long until shoppers see the correction? A nightly build could leave the old advice online for the rest of the day. A publishing system that regenerates the page and refreshes its cached copies when the editor clicks Publish can make that window much shorter. web.dev

    That makes static generation a natural fit for articles, documentation, and product guides. Even a busy newsroom can generate each story when it’s published. The useful question is whether every reader can receive the same copy until the next edit.

    Server-side rendering does the work when someone asks

    With server-side rendering (SSR), the server can use details from an incoming request to decide what goes into the HTML it sends back. Imagine the shopper follows a link to the blue mug and has already selected a Bangkok pickup location. The server can check that branch’s inventory and include “Available for pickup in Bangkok” in the first response. The shopper gets an answer without waiting for the browser to make a second inventory request. web.dev

    That lookup has a cost. If the server waits for a slow inventory system before sending any HTML, the shopper waits too. Saving a rendered response in a cache lets later visitors reuse it. The shop then has two decisions to make. How long is the answer useful, and which visitors does it apply to? A stock figure for Bangkok could be perfectly current and still be the wrong answer for someone collecting in Singapore. MDN

    Even a freshly rendered page captures a moment in time. Two shoppers can both see “one left” while the mug is still on the shelf. The shop has to check and reserve stock when it accepts an order. Rendering determines what the shopper sees. The ordering system determines who gets the mug.

    Client-side rendering puts the browser to work

    With client-side rendering (CSR), JavaScript running in the browser builds or updates the interface. On a fully client-rendered page, the first response may contain little more than an empty container and a reference to a script. The browser downloads and runs the script, fetches any data it still needs, and creates the visible content. On a slow phone or an unreliable connection, the shopper may spend that time looking at a loading indicator. web.dev

    The payoff is easier to see on the second click. Suppose the browser already has the details for each glaze. When the shopper taps green, it can switch the selected swatch and show the matching photo without reloading the description or losing the shopper’s place. If pickup availability for the green mug needs a fresh lookup, just that part of the page needs a loading message.

    This is also where rendering approaches can meet. A server can send HTML with the swatches already visible, and JavaScript can make them respond to taps. In frameworks such as React, attaching the application to that existing HTML is called hydration. It explains a familiar frustration on slower devices. A swatch can look ready before tapping it does anything. Try tapping the first swatch the instant you see it. That tells you something a screenshot never will. React

    How to choose, page by page

    What the visitor wants to doA good starting pointWhat triggers new work?
    Read a guide to caring for handmade ceramicsStatic generationAn editor publishes a correction or adds a care tip.
    Open a product link and see pickup availability at a chosen branchServer-side renderingThe request identifies the product and branch, and the server looks up the relevant stock.
    Compare glaze colors without losing their placeClient-side updatesA tap changes the selection. The browser can reuse product details it already has.
    Browse products, then switch among local shopsA mix of approachesPrepare the catalog ahead of time, show initial stock for a known branch, and refresh availability when the shopper switches shops.

    A revealing test is to open the product link on a phone with a slow connection and try to find out whether you can pick up a green mug today. Watch for three moments. When can you tell you’re on the right product? When does tapping green work? When do you have a pickup answer for your branch? A page can do well on the first question and leave you waiting on the other two.

    Conclusion

    The mug’s capacity, the last item on the shelf, and the shopper’s choice of glaze each become known at a different time. That timing gives you a practical way to choose a rendering strategy. Prepare shared content when it’s published, use the request when the first view depends on current or personal information, and let the browser handle choices people make after arrival. From the shopper’s perspective, it’s one straightforward visit. They can read about the mug, choose a color, and see where to pick it up.