Give Fetch a Deadline Without Losing Caller Cancellation
- Get link
- X
- Other Apps
Give Fetch a Deadline Without Losing Caller Cancellation
A request that never finishes is more than a slow interface: it can leave a loading state stuck and waste work the user no longer needs. A timeout alone is not always enough, either. A search box, route change, or parent task may need to cancel the same request before its deadline.
The Fetch API accepts an AbortSignal. Use AbortSignal.timeout() to set a deadline and AbortSignal.any() to combine that deadline with a signal owned by the caller. This gives one request a clear lifetime without building a custom timer race.
Set a deadline and accept cancellation
async function fetchJson(url, { signal: callerSignal, timeoutMs = 8_000 } = {}) { const timeoutSignal = AbortSignal.timeout(timeoutMs); const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal; const response = await fetch(url, { signal }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); } The request ends if either signal aborts. A UI can cancel its work by passing an AbortController signal:
const controller = new AbortController(); cancelButton.addEventListener('click', () => controller.abort(), { once: true }); try { const results = await fetchJson('/api/search?q=signals', { signal: controller.signal, }); renderResults(results); } catch (error) { if (controller.signal.aborted) { // The caller cancelled this operation; it is no longer relevant to the UI. return; } // Let the application's normal error handling report a timeout or other failure. throw error; } Create a fresh controller for each operation. An aborted signal is one-shot: reusing it for another fetch means that request is already cancelled. The optional caller signal also makes the helper compose naturally: a page, component, or parent task can decide when its work is no longer needed, while the helper still enforces its own deadline.
Why not race a timer against fetch?
Promise.race() chooses which promise settles first; it does not, by itself, stop the losing operation. A timer can make your code stop waiting while the fetch continues. Passing an abort signal to fetch() connects the cancellation decision to the operation itself.
Keep the status check, too. Fetch normally fulfills with a Response even for HTTP errors such as 404, so a fulfilled fetch is not automatically a successful request. And because the signal remains attached while the response body is read, the body parsing in response.json() can also be interrupted.
Know what the deadline means
AbortSignal.timeout() measures active time, not necessarily wall-clock time. In a browser, its countdown can pause while a document is in the back-forward cache or a worker is suspended. Treat it as a useful client-side request deadline, not a guarantee that exactly that many wall-clock milliseconds have elapsed.
When a timeout or cancellation occurs, handle it as an expected end to the operation rather than reporting every abort as an unexpected network failure. If your interface or telemetry must distinguish a user cancel from a timeout, track those causes explicitly; do not assume the combined signal's rejection alone always identifies which one happened. Also remember that cancelling a client request is not a rollback guarantee for work a server has already begun, especially for writes.
These APIs are available in current browsers and in supported Node.js releases, but check your runtime baseline before adopting them in older environments. AbortSignal.any() reached Node.js in v18.17.0 and v20.3.0; the Node documentation lists the version history. If you need compatibility with older runtimes, combine signals with an AbortController and ensure any listeners and timers are cleaned up.
The practical rule is simple: give each request an owner, give it a deadline, and pass the combined signal all the way to the asynchronous operation. That makes cancellation part of the operation's contract instead of an afterthought.
References
- MDN: AbortSignal
- MDN: AbortSignal.timeout()
- MDN: Using the Fetch API
- Node.js: AbortSignal
- WHATWG Fetch Standard
❤️ Support This Blog
If this post helped you, you can support my writing with a small donation. Thank you for reading.
- Get link
- X
- Other Apps

Comments
Post a Comment