Promise with Timeout

MediumUtility Functions15 min4 tests

Implement a withTimeout function that wraps a promise with a timeout. If the promise doesn't resolve within the specified time, reject with a "Timeout" error message.

Requirements

  • Accept a promise and a timeout in milliseconds
  • If the promise resolves before the timeout, return its value
  • If the timeout expires first, reject with the string "Timeout"
  • Clean up the timer when the promise resolves to avoid memory leaks

Example

await withTimeout(fetch('/api'), 5000); // Rejects with "Timeout" after 5s
await withTimeout(Promise.resolve(42), 1000); // Resolves with 42
Hints (4)
  1. Use Promise.race to race the original promise against a timeout promise.
  2. Create a new promise that rejects after the specified milliseconds.
  3. Use setTimeout inside the timeout promise.
  4. Clear the timeout when the original promise resolves to prevent leaks.

Topics

  • Utility Functions

Asked at

Google · Meta · Netflix · Uber

Join Us
blur