JavaScript · Senior · Question 51 of 75

How do you abort a fetch after 5 seconds or when the user navigates away, whichever comes first?

const signal = AbortSignal.any([AbortSignal.timeout(5000), controller.signal]);
await fetch(url, { signal });

Explanation

fetch has no timeout option. AbortSignal.timeout rejects with a TimeoutError, while a manual abort gives an AbortError, so you can tell them apart.

Further reading

Problem with a question

JavaScript · Senior · question 51

Test yourself

Take the JavaScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz