Skip to content
CoursesWeb Forum

How do I show a loading spinner while fetch waits for the server

Asked by Marisa T. · JavaScript Events, Timers and Fetch2 repliesupdated

Short answer

I am learning JavaScript for test automation and I am building a small page to practise. A button loads a list of orders from a JSON file on the server. The server is slow on purpose (I added a 3 second delay) so I can test loading states. I want a spinner to show while the request is running, and to disappear when the data has arrived, or when the request failed.

Written by Marisa T. ·
CiteCoursesWeb Forum, "How do I show a loading spinner while fetch waits for the server", https://coursesweb.net/forum/t/how-do-i-show-a-loading-spinner-while-fetch-waits-for-the-server/, accessed 2026-12-05.
  1. Member ·

    My first version:

    const spinner = document.querySelector("#spinner");
    const list = document.querySelector("#orders");
    
    async function loadOrders() {
      spinner.hidden = false;
      const response = await fetch("/data/orders.json");
      const orders = await response.json();
      list.textContent = orders.map((o) => o.name).join(", ");
      spinner.hidden = true;
    }
    
    document.querySelector("#load").addEventListener("click", loadOrders);
    

    It works when everything goes well. But my test with a wrong URL ("/data/missing.json") leaves the spinner spinning forever. I also noticed that if I press the button twice, two requests run.

    What is the correct pattern for a loading state that always ends, including after an error? And how do you keep a double click from sending two requests? I want to be able to reproduce each case, so tips on testing it are welcome too.

    1
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. Ferdi K.Member ·

    I would hide the spinner with setTimeout after 3 seconds. Attempt 1 for me and it looked fine, the spinner was gone by the time the data showed up. I did not try it with the slow server yet, so maybe it is luck.

  2. Kaveh S.Member ·

    just move spinner.hidden = true to right after the fetch( line, before the await. thats when the request is done? i think the line after fetch only runs once it finishes, right? i am not sure how async stuff works yet

CoursesWeb Forum. Questions and answers on learning web development: HTML, CSS, JavaScript, PHP, MySQL, Node.js and AI coding help.