#Promises#Async

Promise Time Limit

Wrap an async function so it gives up after a deadline — the building block behind every request timeout.

By Pratik RaiMedium

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

Input:

JSfile.javascript
1const limited = timeLimit(async (n) => { 2 await new Promise((r) => setTimeout(r, 100)); 3 return n * 2; 4}, 50); 5limited(5).catch(console.log);

Output:

"Time Limit Exceeded"

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.

Goal: Reject with "Time Limit Exceeded" past the deadline, and pass everything else through untouched.

Source

Frequently asked questions

How do you add a timeout to a promise?
Race the promise against a timer that rejects. `Promise.race` settles with whichever finishes first, and because a promise settles only once the loser is ignored automatically.
Does a timeout cancel the underlying work?
No. The original promise carries on and its result is discarded — the timeout only stops you waiting. Cancelling a real request needs `AbortController` passed to `fetch`.
Why clear the timer after the race settles?
A pending timer keeps the event loop alive, which delays process exit in Node and leaks a callback in a long-lived page. Clearing it in `finally` covers both the success and failure paths.
Should a timeout replace the original error?
No. If the wrapped function rejects on its own, that rejection should pass through unchanged. Replacing it with a generic timeout hides the real cause and makes the failure much harder to debug.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Promise Pool

Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.

JavaScript · ES6Pratik Rai ·

JavaScript

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

JavaScript · ES6Pratik Rai ·

JavaScript

Resolve Promises Sequentially

Run promises one after another and collect the results in order — built with .then chaining, no async/await.

JavaScript · ES6Pratik Rai ·