CodePark/ problems / Promise with a time limit
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Async control flow

Promise with a time limit

easyabout 12 minutes in an interview

Implement promiseTimeout(promise, ms). It returns a new promise. If promise settles within ms milliseconds, the new promise settles the same way. Settles means resolves or rejects.

  • If promise resolves or rejects first, pass on its value or reason.
  • If ms ms pass first, reject with an Error whose message is exactly Timed out after <ms> ms. For example: Timed out after 100 ms. A late result from promise is then ignored.
  • When promise settles in time, clear the timer so nothing is left pending.
Input: await promiseTimeout(wait(50, 'ok'), 100) Output: 'ok'
Input: await promiseTimeout(wait(500, 'ok'), 100) Output: rejects with Error('Timed out after 100 ms') at 100 ms