Code
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export async function fetchWithRetry(url, { retries = 3, timeout = 5000, backoff = 500, ...opts } = {}) {
for (let attempt = 0; ; attempt++) {
try {
// Eigener Timeout pro Versuch
const res = await fetch(url, { ...opts, signal: AbortSignal.timeout(timeout) });
// Nur 429 und 5xx wiederholen, 4xx direkt zurückgeben
if ((res.status === 429 || res.status >= 500) && attempt < retries) {
throw new Error(`HTTP ${res.status}`);
}
return res;
} catch (err) {
if (attempt >= retries) throw err;
// Exponentieller Backoff mit Jitter
await sleep(backoff * 2 ** attempt + Math.random() * 100);
}
}
}
// in async-Funktion:
// const res = await fetchWithRetry('/api/data', { timeout: 3000, retries: 2 });