Lesson 4 of 8
Retrying
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
Don't give up after the first failure
Explanation
Many network errors are temporary, like a momentary drop in the connection or a busy server, and retrying a couple of times is enough for most requests to succeed without the user noticing a thing.
A simple loop does the job: try, and if it fails and you still have attempts left, wait a little and try again. If you run out of attempts, throw the last error instead of silently swallowing it.
Make the wait between attempts grow each time, which is called backoff, because hammering an overloaded server with rapid requests only adds to its load.
Your task
Write the function withRetry(fn, times), which keeps retrying until it succeeds or runs out of attempts. Then make the button call withRetry(flaky, 3) so the page shows the status and the number of attempts.
Checks
5 checks- withRetry is defined
- It succeeds even though the first two attempts fail
- It took three attempts
- Running out of attempts throws the error instead of ignoring it
- It returns the function's value when the first try succeeds