Retry With Backoff
NodeJS
Hard
5 views
Problem Description
Retry a failing async function 3 times with small delays.
Output Format
Print attempt count.
Constraints
Use async loop with await delay.
Official Solution
function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
let attempts = 0;
async function job() {
attempts += 1;
throw new Error('fail');
}
(async () => {
for (let i = 0; i < 3; i++) {
try {
await job();
break;
} catch (e) {
if (i < 2) await sleep(20 * (i + 1));
}
}
console.log(attempts);
})();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!