Write a function `withTimeout(promise, ms)` that rejects if the promise does not resolve within `ms` milliseconds.
Problem Statement
Write a function `withTimeout(promise, ms)` that rejects if the promise does not resolve within `ms` milliseconds.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Race the original promise against a timeout promise.
š” Hint 2:
Create a timeout promise that rejects after ms milliseconds.
š” Hint 3:
return Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), ms))]);
ā
Solution:
```javascript
function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), ms));
return Promise.race([promise, timeout]);
}
```