Loading...
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
const res = await fetch(url, { signal: controller.signal });try {
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
} catch (err) {
if (err.name === 'TimeoutError') showRetry();
}AbortSignal.timeout() needs no manual timer and rejects with a 'TimeoutError', which is easy to tell apart from user aborts.
AbortSignal.timeout(ms), not setTimeout with controller.abort().catch handles 'TimeoutError' separately from other errors.The fetch rejects with a DOMException named 'TimeoutError', not 'AbortError'.
Yes, the signal stays attached, so reading the body with res.json() is aborted too if time runs out.