Why should you clearTimeout after a Promise.race timeout in JavaScript?
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.
Verify This Answer
Cross-check this information using these trusted sources:
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.
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.
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
