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
fncompletes within the time limit oftmilliseconds, the time limited function should resolve with the result. - If the execution of the
fnexceeds 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code