Facebook Pixel
Implementing Timeout with Promises in JavaScript

How do you cancel a fetch with a timeout in JavaScript?

The answer

Use AbortController: const controller = new AbortController(); fetch(url, { signal: controller.signal }). Set a timeout to call controller.abort(). This actually cancels the fetch, not just races it.

More FAQs in Implementing Timeout with Promises in JavaScript

Use Promise.race: race the operation against a timeout promise. Promise.race([fetch('/api'), new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 5000))]). If the timeout fires first, the race rejects.

To avoid a memory leak. The timeout promise's timer keeps running even after the race settles. clearTimeout cancels the timer. Use try/finally to clear it regardless of outcome.

No. Promise.race does not cancel the other promises. They continue running; their results are just ignored. For actual cancellation, use AbortController (with fetch) or implement your own cancellation logic.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.