Timeout any promise with Promise.race
Whichever settles first wins. Works for any promise, not only fetch.
JavaScript · Timeout any promise with Promise.raceAdvanced
function withTimeout(promise, ms, message = 'Timed out') {
let timer;
const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); });
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
const slow = new Promise((resolve) => setTimeout(() => resolve('late'), 200));
const result = withTimeout(slow, 20).catch((e) => e.message);promise.racetimeoutasync