FrontendInterviews.dev

Loading problem…

104. Promise Timeout

Medium•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

Implement promiseTimeout that applies a timeout to a promise.

Requirements

  • Accept a promise and timeout in milliseconds
  • Resolve with original value if promise settles before timeout
  • Reject with timeout error if timer fires first
  • Clear timer after promise settles to avoid leaks

Signature

function promiseTimeout(promise, timeoutMs)

Example Usage

// Example: Resolves before timeout
const fastPromise = new Promise(resolve => setTimeout(() => resolve('ok'), 10));

promiseTimeout(fastPromise, 50).then(value => {
  console.log(value); // 'ok'
});

// Example: Rejects on timeout
const slowPromise = new Promise(resolve => setTimeout(() => resolve('late'), 100));

promiseTimeout(slowPromise, 20).catch(error => {
  console.log(error.message); // 'Timeout'
});

Constraints

  • timeoutMs >= 0
  • If timeout wins, reject with Error('Timeout')
  • Do not leave dangling timers