JavaScript Fetch Timeout That Covers the Response Body
Keep cancellation active until JSON parsing finishes, and test the slow-body case that a headers-only timeout misses.
Checked against the official docs on Nov 14, 2026.

Pass an abort signal to fetch() to give a request a timeout. In runtimes that support it, AbortSignal.timeout(milliseconds) supplies the deadline signal, and AbortSignal.any() lets the same request respond to a user cancellation.
The local server example and both request functions were tested on November 14, 2026 with Node.js 24.22.1 on Linux. Both functions passed success, timeout, HTTP error, invalid JSON, already-aborted signal, and active cancellation cases.
Keep the deadline active through body reading
A fetch promise can resolve when response headers arrive while the body is still downloading. Put body reading inside the operation governed by your timeout. The function below waits for the response, rejects unsuccessful HTTP statuses, and parses JSON before returning a value.
async function fetchJson(url, { timeoutMs = 5000, signal } = {}) {
const deadline = AbortSignal.timeout(timeoutMs);
const combined = signal
? AbortSignal.any([signal, deadline])
: deadline;
const response = await fetch(url, { signal: combined });
if (!response.ok) {
if (response.body) await response.body.cancel();
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
}The timeout in this example is a chosen application default. Select it according to the interaction you are designing, and expose a shorter value in tests. A background report download and a search-as-you-type request can have very different acceptable waiting times.
Fetch normally returns a response for HTTP error statuses, so checking response.ok is an application responsibility. Reading JSON can also fail because the body is invalid or interrupted. Keep those failures visible to the caller. The existing JavaScript fetch tutorial introduces response handling and JSON requests. MDN fetch behavior
Reproduce a slow body with a local server
A useful timeout test makes headers arrive immediately and delays the body. This catches implementations that clear their timeout as soon as fetch returns a response. Save the following as fetch-timeout-demo.mjs and run it with a Node.js version that provides fetch and AbortSignal.timeout().
import http from "node:http";
import { once } from "node:events";
const server = http.createServer((request, response) => {
response.writeHead(200, { "Content-Type": "application/json" });
response.flushHeaders();
const timer = setTimeout(() => response.end('{"ready":true}'), 500);
response.on("close", () => clearTimeout(timer));
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
const { port } = server.address();
const deadline = AbortSignal.timeout(100);
try {
const response = await fetch(`http://127.0.0.1:${port}`, {
signal: deadline,
});
console.log("headers received:", response.status);
await response.json();
throw new Error("The delayed body unexpectedly completed");
} catch (error) {
if (!deadline.aborted) throw error;
console.log("deadline reason:", deadline.reason.name);
console.log("body read stopped:", error.name);
} finally {
const closed = once(server, "close");
server.close();
server.closeAllConnections();
await closed;
}The server binds to loopback and lets the operating system select an available port. The delayed response and short timeout are test inputs. Run the example on a quiet development machine, then repeat it with a larger deadline to observe successful body completion after adapting the deliberate success-path assertion.
Inspect the signal's reason as well as the caught error. Different parts of a cancelled request can surface different exception names. The signal tells you whether the deadline fired, while the error explains where the operation stopped. Record both in a test when diagnosing runtime differences. Node documents its abort globals and timeout signal API. Node.js abort-signal reference
Combine a cancel button with a deadline
Create a new controller for each user operation. Keep its controller available to the cancel button, and pass its signal into the function. An aborted signal remains aborted, so a retry needs a fresh controller and a fresh deadline.
const controller = new AbortController();
cancelButton.onclick = () => controller.abort();
try {
const data = await fetchJson("/api/report", {
timeoutMs: 8000,
signal: controller.signal,
});
showReport(data);
} catch (error) {
if (controller.signal.aborted) {
showStatus("Cancelled");
} else {
showStatus(`Could not load the report: ${error.message}`);
}
} finally {
cancelButton.onclick = null;
}This integration sketch assumes your page defines the button and display functions, and allows one active report request at a time. Disable the start control during that operation or track requests explicitly. Otherwise an earlier operation's cleanup could remove the cancel handler belonging to a later one.
The combined signal aborts when an input signal aborts, and its reason comes from the first signal that caused cancellation. Passing an already aborted input produces an already aborted combined signal. This is important when wiring request state to a component that may already have been disposed. MDN combined abort signals
Provide a controller-based fallback when needed
Feature detection should match the APIs your function uses. Check for both timeout and signal composition before calling the first implementation. If your supported runtime lacks either method, a controller and timer can express the same request-level intent.
async function fetchJsonWithTimer(url, { timeoutMs = 5000, signal } = {}) {
const controller = new AbortController();
const forwardAbort = () => controller.abort(signal.reason);
if (signal?.aborted) forwardAbort();
else signal?.addEventListener("abort", forwardAbort, { once: true });
const timer = setTimeout(() => {
controller.abort(new DOMException("Request timed out", "TimeoutError"));
}, timeoutMs);
try {
const response = await fetch(url, { signal: controller.signal });
if (!response.ok) {
if (response.body) await response.body.cancel();
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} finally {
clearTimeout(timer);
signal?.removeEventListener("abort", forwardAbort);
}
}The timer is cleared after body parsing settles. The external listener is removed on every exit. Those details matter on a page that starts many requests over its lifetime. Repeatedly leaving listeners attached to a long-lived signal can create a steadily growing cleanup problem.
Browser timeout signals count active time and can pause while execution is suspended, including relevant back-forward cache behavior. A timer fallback also depends on the browser's scheduling rules. Treat the value as a client-side cancellation policy when designing the interface. A server-side deadline needs its own implementation at the server. MDN timeout semantics
Classify failures before offering a retry
For diagnostics, record the request's operation identifier, elapsed time, whether headers arrived, and whether the abort signal fired. Keep these fields separate. An error message alone may collapse a user cancellation, a deadline, and a failed body read into the same visible symptom. Use a monotonic clock such as performance.now() when measuring a duration inside the application.
In the local-server test, add one log immediately after fetch resolves and another after JSON parsing. A run that prints the first log but never reaches the second has narrowed the waiting phase to the body. If neither appears before cancellation, inspect connection establishment and header delivery. This small change often provides more actionable evidence than repeatedly increasing the timeout.
Avoid placing raw response bodies, credentials, or full query strings in routine error logs. A request identifier can connect the browser event to a server-side trace without copying sensitive payloads. For a local reproduction, replace private input with a small fixed JSON object and retain only the timing behavior required to trigger the failure.
Once the failure is reproducible, test the cleanup path too. Close the local server, ensure pending requests settle, and start the test again. Repeated successful runs demonstrate that the fixture releases its resources and that a previous aborted request cannot affect the next case. Run the same cases against both implementations if your application ships the fallback.
| Observation | What to inspect | Useful interface behavior |
|---|---|---|
| Deadline signal aborted | Signal reason and operation phase | Explain that waiting timed out |
| User controller aborted | Current request identifier | Return to an idle or cancelled state |
| HTTP error response | Status and allowed error-body fields | Show an appropriate service error |
| JSON parsing error | Response content type and a safe sample | Report an unexpected response |
| Network failure | Connectivity and server logs | Offer a deliberate retry when appropriate |
Cancellation describes the client's waiting behavior. A server may already have received and processed a request before the client aborts. For an operation that creates a payment, job, or record, use the application's idempotency and status-checking design before retrying. Avoid automatically repeating every failed request with the same generic policy.
Test the interface with a fast response, slow headers, a slow body, invalid JSON, an HTTP error, and a user cancellation. Also cancel an earlier request after a newer request starts and verify that stale results cannot replace the current view. Tracking an operation identifier alongside the controller gives the UI a concrete way to accept only the result it still wants.
Keep the local server example as a small regression fixture. A timeout implementation can look correct during a fast successful request and still fail when the body stalls. Testing the exact phase that previously hung gives future refactors a clear pass condition.
Quick answers
Can fetch finish before its response body has arrived?
Yes. Keep the abort signal active while awaiting response.json or another body-reading method.
Can I reuse an aborted signal for a retry?
Create a fresh controller and timeout signal for the new operation. An aborted signal stays aborted.
Does aborting a request undo server-side work?
The server may already have processed the request. Check operation status and apply your idempotency policy before repeating a state-changing action.
Official sources
Next guide