FrontendInterviews.dev

Loading problem…

104. Promise Timeout

Medium•

The promiseTimeout function wraps a Promise and rejects if it does not settle within a given time.

Implement promiseTimeout(promise, timeoutMs) which returns a new Promise. If the input promise resolves or rejects before the timeout, return its result. Otherwise, reject with new Error('Timeout').

Example

const fast = new Promise(resolve => setTimeout(() => resolve('ok'), 10));
promiseTimeout(fast, 50).then(console.log); // 'ok'

const slow = new Promise(resolve => setTimeout(() => resolve('late'), 100));
promiseTimeout(slow, 20).catch(err => {
  console.log(err.message); // 'Timeout'
});

Constraints

  • timeoutMs >= 0
  • If timeout wins, reject with Error('Timeout')
  • Do not leave dangling timers
Accepted22/28|Acceptance Rate78.6%