Skip to content

Instantly share code, notes, and snippets.

@NithinBiliya
Created February 24, 2025 13:31
Show Gist options
  • Save NithinBiliya/3c4acbf4033ef6cfc3ae6ce9973aca09 to your computer and use it in GitHub Desktop.
Save NithinBiliya/3c4acbf4033ef6cfc3ae6ce9973aca09 to your computer and use it in GitHub Desktop.
async function fetchWithRetry(url, retries = 5, baseDelay = 500) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Request failed');
return await response.json();
} catch (error) {
const jitter = Math.random() * baseDelay;
const delay = baseDelay * Math.pow(2, i) + jitter;
console.log(`Retry ${i + 1}/${retries} failed. Retrying in ${Math.round(delay)}ms...`);
await new Promise(res => setTimeout(res, delay));
}
}
throw new Error('All retries failed');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment