Time Out an Async Function

PromisesAsyncTimers

Write timeLimit(fn, t). It returns a wrapper that takes the same arguments as fn and settles the same way fn does — unless fn is still running after t milliseconds. In that case the wrapper gives up and rejects with "Timed out", a plain string rather than an Error.

Examples

Example 1
Input
const lookup = timeLimit(async (word, ms) => {
  await new Promise((r) => setTimeout(r, ms));
  return word.toUpperCase();
}, 200);

lookup('fast', 80).then(console.log);
lookup('slow', 350).catch(console.log);
Output
FAST
Timed out
Explanation
Both calls get the same 200ms budget. The first finishes at 80ms and its value passes straight through; the second would need 350ms, so it is rejected when the budget runs out at 200ms.

Constraints

  • fn is an async function, so calling it always gives back a promise
  • t is a positive number of milliseconds

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 Time Out an Async Function
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it