JavaScript › Error Handling
How do you implement a retry-with-backoff pattern around a function that might throw?
AdvancedAnswer
Wrap the call in a loop with a try/catch; on failure, wait an increasing delay (e.g. exponential backoff) before retrying, up to a maximum attempt count, then re-throw the final error if all attempts fail.
async function retry(fn, attempts = 3, delay = 500) {
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (err) {
if (i === attempts - 1) throw err;
await new Promise(r => setTimeout(r, delay * 2 ** i));
}
}
}Real-world example Retrying a flaky network request up to three times with increasing delays before giving up and showing an error.