How do I show a loading spinner while fetch waits for the server
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.
Cite
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.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.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.