Timeout wrapper
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return a Promise that settles like `promise` if it settles within `ms` milliseconds. Otherwise reject with `new Error("Timed out")` at `ms`. Clear your timer once the result is known, so nothing is left pending. Tests run on a fake clock: `setTimeout`, `clearTimeout` and `Date.now` are simulated, so waits are instant and exact.
What this exercise teaches
Promise.race settles with whichever side settles first. finally runs on both outcomes, so the timer is cleared whether the work finished, failed or timed out, and an Error object gives callers a proper message and stack.
A hint if you get stuck
Race `promise` against a second Promise that rejects from a `setTimeout`, and clear that timer in `.finally()`.
This exercise is part of Pro
Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.
You create a free account first, so Pro is attached to it.
Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.