A fetch() call that never answers just hangs. The old fix needed an AbortController, a setTimeout and a clearTimeout, and I always forgot one of the three.
try {
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
console.log(await res.json());
} catch (err) {
if (err.name === 'TimeoutError') console.log('too slow');
else throw err;
}
AbortSignal.timeout(ms) returns a signal that aborts itself after the given number of milliseconds. Pass it as signal and the request is cancelled when the time is up.
The detail that matters is the error name. A timeout rejects with a TimeoutError, while a manual controller.abort() gives an AbortError. That lets you tell “the server was slow” from “the user left the page” in one catch.
You can also combine it with a manual cancel through AbortSignal.any([AbortSignal.timeout(5000), controller.signal]).
Two caveats from MDN. The timer counts active time, so it pauses while a page sits in the back-forward cache or a worker is suspended. And a timeout signal cannot be cancelled early, so when you need that, stay with an AbortController plus setTimeout and call clearTimeout when the work finishes. Check the browser support table for your audience, though it is listed as widely available.
Further reading: MDN: AbortSignal.timeout()