FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Promise Timeout

25mins

Implement a function promiseTimeout(promise, ms) that either resolves with the value of the given promise if it finishes within the specified time or rejects with an error if the timeout duration is exceeded.

The function should:

  • Take a promise and a timeout in milliseconds.
  • Resolve with the promise's result if it resolves before the timeout.
  • Reject with an error message like "Timeout" if the timeout is reached first.

Examples

const slowPromise = new Promise(res => setTimeout(() => res("done"), 2000)); promiseTimeout(slowPromise, 1000).catch(console.error); // "Timeout" const fastPromise = new Promise(res => setTimeout(() => res("done"), 500)); promiseTimeout(fastPromise, 1000).then(console.log); // "done"

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests