Why a fetch never resolves
fetch() resolves when the status and headers arrive and rejects on a network error or an abort. It has no timeout option (MDN's list of request options has none), so a request that gets no answer just waits. The request's Timing tab in Chrome DevTools splits its time into phases, and the phase where the time goes tells you which case you have:
| Where it hangs | Timing phase | Usual cause |
|---|---|---|
| Before it is sent | Queueing or Stalled | Over HTTP/1.1, Chrome keeps at most six connections open per origin and queues the rest. Long polls and event streams can hold all six, even from other tabs. |
| Waiting for the answer | Waiting (TTFB) | The server has not answered, or a proxy in front of it is still waiting. nginx's proxy_read_timeout, for one, waits 60 s by default. |
| Reading the body | Content Download | The headers arrived, so fetch() resolved, but the body stopped partway and res.json() waits for the rest. nginx's read timeout counts only the gap between two reads, so a body that trickles in can stay open much longer. |
| In your code | The request has finished | A promise of yours never settles. |
When a proxy does give up, it may answer 504 Gateway Timeout. fetch() resolves with a 504 like any other status, so check res.ok.
The last row is easy to miss. Here a hand-written promise has a path that calls neither resolve nor reject:
function loadItems() {
return new Promise((resolve, reject) => {
fetch("/api/items")
.then((res) => {
if (!res.ok) return; // a 500 calls neither resolve nor reject
return res.json().then(resolve);
})
.catch(reject);
});
}
On a 500, await loadItems() never returns. Drop the wrapper and write an async function that throws when !res.ok, so every path settles.
Add a timeout with AbortSignal.timeout()
Pass a signal that aborts itself after a set time. When it fires, fetch() rejects with a DOMException named TimeoutError, and your catch and finally run:
async function loadReport(id) {
const res = await fetch(`/api/reports/${id}`, { signal: AbortSignal.timeout(10_000) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json(); // the same 10 s limit still covers the body
}
The clock starts when you call AbortSignal.timeout(), so create the signal for each request, not once for the page. MDN notes that it counts active time, so it pauses while the page sits in the back-forward cache.
Combine the timeout with a cancel button
A request takes one signal. To stop it on whichever comes first, the time limit or the user, merge two signals with AbortSignal.any(). The merged signal aborts with the reason of the first one that fires:
const userCancel = new AbortController();
cancelButton.addEventListener("click", () => userCancel.abort());
const timeout = AbortSignal.timeout(15_000);
try {
const res = await fetch("/api/export", { signal: AbortSignal.any([userCancel.signal, timeout]) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
showExport(await res.json());
} catch (err) {
if (timeout.aborted) showError("No answer after 15 seconds. Try again.");
else if (!userCancel.signal.aborted) showError(err.message); // network error or HTTP status
} finally {
spinner.hidden = true;
}
Normally err.name tells them apart: TimeoutError when the limit fired, AbortError when your controller aborted. The code checks which signal aborted instead, because in Chrome and Edge 103 to 123 AbortSignal.timeout() aborted with an AbortError (MDN's compatibility table).
MDN marks both methods Baseline, widely available: AbortSignal.any() has worked across browsers since March 2024 and AbortSignal.timeout() since April 2024. Older browsers can lack them, so feature-detect and fall back to a helper:
function anySignal(signals) {
if (AbortSignal.any) return AbortSignal.any(signals);
const controller = new AbortController();
for (const s of signals) {
if (s.aborted) { controller.abort(s.reason); break; }
s.addEventListener("abort", () => controller.abort(s.reason), { once: true });
}
return controller.signal;
}
Where AbortSignal.timeout() is missing, a controller and setTimeout do the same job, as in the next section. Aborting the previous request when a new one starts also keeps out-of-order responses off the screen.
Make the limit cover res.json() too
fetch() resolves when the headers arrive, possibly before the body. If the signal aborts after that, reading the body rejects as well, so a signal from AbortSignal.timeout() covers res.json() with no extra code. A timer you build yourself covers it only if you clear the timer after the body is read:
async function getJSON(url, ms = 10_000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const res = await fetch(url, { signal: controller.signal });
// clearTimeout(timer) here would leave res.json() with no limit
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} finally {
clearTimeout(timer);
}
}
When time runs out, this version rejects with an AbortError.
How axios timeouts differ
axios has the timeout option that fetch lacks, but it defaults to 0, which means no timeout, and the axios README tells you to set one in production. In the browser axios uses XMLHttpRequest unless you choose its fetch adapter. XMLHttpRequest's own timeout, also 0 by default, limits how long the whole request can take. axios resolves only after the body has arrived, so one number covers both.
try {
const { data } = await axios.get("/api/report", { timeout: 10_000 });
render(data);
} catch (err) {
if (err.code === "ECONNABORTED" || err.code === "ETIMEDOUT") showError("No answer after 10 seconds.");
else if (!axios.isCancel(err)) showError(err.message);
}
The errors differ too. An axios timeout rejects with an AxiosError whose code is ECONNABORTED, or ETIMEDOUT with transitional.clarifyTimeoutError or the fetch adapter. The XMLHttpRequest adapter also uses ECONNABORTED when the browser aborts a request. A signal that aborts, even one from AbortSignal.timeout(), rejects with a CanceledError (code ERR_CANCELED), so a timeout passed that way looks like a cancel unless you check the signal. axios also rejects any status outside 2xx by default, where fetch() resolves with it.
Retry only idempotent requests, with backoff
A timeout does not tell you whether the server did the work. RFC 9110 counts GET, HEAD, OPTIONS, PUT and DELETE among the idempotent methods: sending one of them twice has the same effect as sending it once. It says a client should not retry other methods automatically unless it knows the request is idempotent or was never applied. A POST that timed out may already have created the order, so give it an idempotency key before any retry (see preventing duplicate submissions).
const RETRY_METHODS = ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"];
const RETRY_STATUS = [502, 503, 504];
async function fetchWithRetry(url, init = {}, { tries = 2, timeoutMs = 10_000 } = {}) {
const method = (init.method ?? "GET").toUpperCase();
for (let attempt = 1; ; attempt++) {
const last = attempt >= tries || !RETRY_METHODS.includes(method);
const timeout = AbortSignal.timeout(timeoutMs); // a new limit for each try
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
try {
const res = await fetch(url, { ...init, signal });
if (last || !RETRY_STATUS.includes(res.status)) return res;
} catch (err) {
if (last || init.signal?.aborted) throw err; // never retry a user cancel
}
const wait = 500 * 2 ** (attempt - 1); // doubles after each try
await new Promise((r) => setTimeout(r, wait / 2 + Math.random() * (wait / 2)));
}
}
The random part of the wait keeps many clients from retrying at the same moment. If a 503 carries a Retry-After header, wait that long instead. The same RFC section says a client should not automatically retry a failed automatic retry, which is why tries defaults to 2: the request and one retry.
No spinner without a time limit
When a spinner never stops or a submit button stays disabled, look at where the code resets it. A reset in a finally block after an await, or in a .finally() callback, runs only once the request's promise settles. Make it a rule that every request a loading state waits on has a time limit, and tell the user what happened when it runs out:
async function onSave(event) {
event.preventDefault();
saveButton.disabled = true;
try {
const res = await fetch("/api/profile", {
method: "PUT",
body: new FormData(event.target),
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
showMessage("Saved.");
} catch {
showMessage("Saving failed or timed out. Your changes are still here, so try again.");
} finally {
saveButton.disabled = false; // now it always runs
}
}
TanStack Query has no timeout option either. It passes each query function a signal and aborts it when the query goes out of date or inactive, but a request that never answers keeps isLoading true. Merge its signal with your own:
useQuery({
queryKey: ["report", id],
queryFn: async ({ signal }) => {
const res = await fetch(`/api/reports/${id}`, {
signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
},
});
It retries a failed query three times by default, with waits that double from one second, so four 15-second timeouts can keep the spinner up for more than a minute. Lower retry for queries a user is waiting on.
Where GenClass fits
GenClass is an open-source browser library that watches an app's requests. Its measured check request-stalled reports a fetch or XHR request still pending after 15 seconds, once per request, with its method, host, path and how long it has waited, and the control the page disabled or marked aria-busy for it. On GenClass's six demo apps in headless Chromium, it found a planted 60-second hang in 11 of 18 runs, with 0 false reports in 120 runs (60 clean, 60 with simulated slowdowns and failures). None of the apps that stalled disables a control while it waits, so naming the control is covered by unit tests only. It skips long polls on a schedule it has learned, event streams, WebSockets and endpoints that usually take that long. It stops counting a fetch once the headers arrive, so a body that stalls after them is not reported. It is one of the measured visual checks, so it is on by default on development hosts, and on a live site only if you turn it on.
When the on-device model is loaded, it is also asked about a request that runs long for its endpoint. Once five requests to that endpoint have succeeded in the page load, long means past the largest of 4 times their median, 2 times their p95 and 0.5 s; with no history, past 10 s. The model can diagnose it as slow, and GenClass publishes no detection rate for that diagnosis. In the default observe mode both are reports only, and adding the timeout stays your job. To try it, run npx genclass in your app's folder.
Questions
Does fetch have a default timeout?
No. fetch() has no timeout option and waits until an answer or a network error arrives; pass signal: AbortSignal.timeout(ms) to set your own limit.
What is the default timeout in axios?
0, which means no timeout. Set timeout in milliseconds on a request or an instance; a timeout then rejects with the code ECONNABORTED, or ETIMEDOUT with the fetch adapter.
Why is isLoading stuck at true?
The promise behind it has not settled, and a request with no time limit can wait as long as the server stays silent. Add a timeout so the request fails and the loading state ends.
Does keepalive stop a fetch from hanging?
No. keepalive lets a request with a body of up to 64 KiB finish after the page unloads, and it sets no time limit.
Why does a request stay pending in Chrome DevTools?
Either the browser has not sent it yet because six HTTP/1.1 connections to that origin are already open, or the answer or its body has not finished arriving. The Timing tab shows which phase the time is in.
Related: race conditions in JavaScript and frontend bug monitoring.