Promise Time Limit - Problem

Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. The function fn takes arguments provided to the time limited function.

The time limited function should follow these rules:

  • If the fn completes within the time limit of t milliseconds, the time limited function should resolve with the result.
  • If the execution of the fn exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded".

Input & Output

Example 1 — Function Completes in Time
$ Input: fn = async () => { await new Promise(res => setTimeout(res, 50)); return 'result'; }, t = 100
Output: 'result'
💡 Note: Function takes 50ms to complete, which is within the 100ms limit, so it resolves with 'result'
Example 2 — Function Times Out
$ Input: fn = async () => { await new Promise(res => setTimeout(res, 200)); return 'result'; }, t = 100
Output: Time Limit Exceeded
💡 Note: Function takes 200ms but timeout is 100ms, so the timeout promise rejects first with 'Time Limit Exceeded'
Example 3 — Immediate Resolution
$ Input: fn = async () => 42, t = 50
Output: 42
💡 Note: Function resolves immediately with 42, well within the 50ms timeout

Constraints

  • 0 ≤ t ≤ 1000
  • fn returns a promise

Visualization

Tap to expand
Promise Time Limit: Adding Timeout to Async Functionsasync fntimeoutt msInput FunctionTime LimitTime LimitedFunctionSuccessTimeout Errorfn completes in timefn takes too longTwo possible outcomes based on timing
Understanding the Visualization
1
Input
Async function fn and timeout t milliseconds
2
Process
Race function execution against timeout
3
Output
Return result if completes in time, else reject with timeout
Key Takeaway
🎯 Key Insight: Use Promise.race to elegantly handle timeout vs function completion
Asked in
Meta 25 Google 20
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen