Retry with backoff
Implement retry(task, { retries, baseMs }). Call task(), which returns a promise. If it rejects, wait baseMs * 2 ** attempt milliseconds (attempt is 0 for the first retry) and call it again, up to retries more times. Resolve with the first success. After the last failure, reject with that error. Use setTimeout for the wait. In the tests the task fails a given number of times with Error('fail N') and then resolves with ok; the answer shows the outcome [status, value, time] and the time of every attempt.
Start from
function retry(task, { retries, baseMs }) {
// Call task again after a growing wait, up to retries more times.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
An async function with a loop reads best: try the task, and in catch decide to give up or to wait.
Hint 2
The wait is a promise around setTimeout: await new Promise((resolve) => setTimeout(resolve, ms)).
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
async function retry(task, { retries, baseMs }) {
for (let attempt = 0; ; attempt++) {
try {
return await task();
} catch (error) {
if (attempt >= retries) throw error;
await new Promise((resolve) => setTimeout(resolve, baseMs * 2 ** attempt));
}
}
}What an interviewer looks for
Flaky networks are normal. Interviewers want a bounded number of attempts and a growing wait, and they ask which requests are safe to retry at all.