Skip to content
Onsite

Promise with Timeout

MediumP2Coding

Implement withTimeout(promise, ms), which returns a promise that follows promise but gives up after ms milliseconds.

  • If promise resolves within ms, the result resolves with the same value.
  • If promise rejects within ms, the result rejects with the same reason.
  • If promise is still pending after ms, the result rejects with an Error whose message is "Timed out after <ms> ms" (for example "Timed out after 50 ms").

Once the result has settled, the timer must not keep running. The original promise is not cancelled; its late outcome is simply ignored.

Example 1

Input
withTimeout(delay(10, 'ok'), 50) withTimeout(delay(100, 'ok'), 50)
Output
resolves with 'ok' rejects with Error('Timed out after 50 ms')

Constraints

  • 0 <= ms <= 10^4
  • promise is a promise or a plain value.

Hints

Run checks the 3 visible tests, Submit all 8.