Automatically retry failed HTTP requests with exponential backoff.
Code
Generalasync function retryFetch(url, retries, delay = 1000) {
for (let i = 0; i <= retries; i++) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response;
} catch (err) {
if (i === retries) throw err;
console.log(`Attempt ${i + 1} failed, retrying in ${delay}ms...`);
await new Promise(r => setTimeout(r, delay));
delay *= 2; // Exponential backoff
}
}
}
const response = await retryFetch(url, maxRetries);
return { status: response.status, ok: response.ok };Parameters
URL to fetch (this one randomly returns 200 or 500)
Maximum retry attempts
Browser·fetch() may be limited by CORS
How It Works
- Loop - Try up to
maxRetries + 1times (initial + retries) - Check response.ok - Treat non-2xx status as failure
- Exponential backoff - Double the delay after each failure (1s → 2s → 4s)
- Rethrow on final failure - If all retries exhausted, throw the last error
Advanced Version
async function retryFetch(url, options = {}) {
const {
maxRetries = 3,
initialDelay = 1000,
maxDelay = 30000,
retryOn = [408, 429, 500, 502, 503, 504],
...fetchOptions
} = options;
let delay = initialDelay;
for (let i = 0; i <= maxRetries; i++) {
try {
const response = await fetch(url, fetchOptions);
if (!response.ok && retryOn.includes(response.status)) {
throw new Error(`HTTP ${response.status}`);
}
return response;
} catch (err) {
if (i === maxRetries) throw err;
await new Promise(r => setTimeout(r, delay));
delay = Math.min(delay * 2, maxDelay);
}
}
}
Test URLs
https://httpbin.org/status/200,500- Randomly succeeds or fails (great for testing retries)https://httpbin.org/status/200,200,500- 66% success ratehttps://httpbin.org/status/200- Always succeedshttps://httpbin.org/status/500- Always fails
More JavaScript Snippets
Add Query Parameter
Add or update a query parameter in a URL string.
Bearer Token Authentication
Make an authenticated HTTP request using Bearer token for JWT or OAuth.
Check Cloudflare Cache Status
Check if a resource is served from Cloudflare's cache by inspecting the CF-Cache-Status header.
CORS Cross-Origin Request
Make a cross-origin HTTP request with CORS headers inspection.
Delayed Response (Test Timeouts)
Request a delayed response to test timeout handling with AbortController.
Download Binary File
Download an image or binary file and convert it to a blob or base64.