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

Source: https://coursesweb.net/forum/t/how-do-i-show-a-loading-spinner-while-fetch-waits-for-the-server/
Site: CoursesWeb Forum, category JavaScript Events, Timers and Fetch
Published: 2026-12-04. Updated: 2026-12-04. Replies: 2.

## Question by Marisa T., 2026-12-04

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.

My first version:

```js
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.

## Reply 1 by Ferdi K., 2026-12-04

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.

## Reply 2 by Kaveh S., 2026-12-04

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

---
Cite as: CoursesWeb 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.
