Promise Time Limit

PromisesAsyncTimers

Write timeLimit(fn, t). It returns a new function that takes the same arguments as fn and behaves identically, except that if fn has not settled within t milliseconds the returned promise rejects with the string "Time Limit Exceeded".

Examples

Example 1
Input
const limited = timeLimit(async (n) => {
  await new Promise((r) => setTimeout(r, 100));
  return n * 2;
}, 50);
limited(5).catch(console.log);
Output
"Time Limit Exceeded"
Explanation
The wrapped function needs 100ms but only has 50ms.

Constraints

  • 0 <= t <= 1000
  • fn returns a promise

Notes

  • A rejection from fn itself must pass through unchanged rather than becoming a timeout.
  • Clear the timer once the race settles, either way.

Hints

Read the full write-up for Promise Time Limit
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it