Promise Time Limit - Problem

You're a performance optimization engineer at a tech company dealing with unreliable external API services. Your task is to create a time-limited wrapper for asynchronous functions to prevent your application from hanging indefinitely.

Given an asynchronous function fn and a time limit t in milliseconds, you need to return a new function that enforces this time constraint:

  • โœ… If fn completes within the time limit, return its result
  • โŒ If fn exceeds the time limit, reject with "Time Limit Exceeded"

The time-limited function should accept the same arguments as the original function and maintain proper error handling for both timeout scenarios and regular function failures.

Example: If you have an API call that should complete within 1000ms, but sometimes takes 3000ms due to network issues, your wrapper should automatically timeout and reject after 1000ms.

Input & Output

example_1.js โ€” Fast API Call
$ Input: fn = async () => { await new Promise(resolve => setTimeout(resolve, 50)); return "Success!"; }, t = 100
โ€บ Output: "Success!"
๐Ÿ’ก Note: The function completes in 50ms, which is well within the 100ms time limit, so it returns the successful result.
example_2.js โ€” Slow API Call
$ Input: fn = async () => { await new Promise(resolve => setTimeout(resolve, 200)); return "Success!"; }, t = 100
โ€บ Output: "Time Limit Exceeded" (rejected)
๐Ÿ’ก Note: The function takes 200ms but the time limit is only 100ms, so the timeout promise wins the race and rejects with the timeout message.
example_3.js โ€” Function with Error
$ Input: fn = async () => { await new Promise(resolve => setTimeout(resolve, 50)); throw new Error("API Error"); }, t = 100
โ€บ Output: Error("API Error") (rejected)
๐Ÿ’ก Note: The function completes within the time limit but throws an error, so that error is properly propagated rather than being masked by a timeout.

Visualization

Tap to expand
๐Ÿ Promise Racing Championship๐ŸŽฏ Original Function LaneProcessing API request, fetching data...โฐ Timeout Promise LaneCounting down milliseconds until deadline...๐Ÿƒโ€โ™‚๏ธโฑ๏ธ๐ŸFINISH๐ŸŽฏ Promise.race() Magicโ€ข No polling overhead - let event loop handle timingโ€ข Automatic cleanup of losing promiseโ€ข Clean error handling for both scenariosโ€ข Scales perfectly with thousands of concurrent operations
Understanding the Visualization
1
Starting Line
Both the original function and timeout promise start executing simultaneously
2
The Race
Function processes data while timeout counts down - no interference between them
3
First to Finish
Promise.race() automatically resolves with whichever promise completes first
4
Victory & Cleanup
Winner's result is returned, loser is automatically cleaned up by JavaScript engine
Key Takeaway
๐ŸŽฏ Key Insight: Promise.race() leverages JavaScript's event loop to efficiently manage concurrent operations without polling, making it the optimal solution for timeout scenarios.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(1)

Constant time setup, actual time depends on which promise resolves first

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only creates two promises and a timer reference

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค t โ‰ค 104 (timeout in milliseconds)
  • The function fn returns a Promise
  • The returned function should maintain the same signature as fn
  • Time limit should be enforced precisely
Asked in
Netflix 35 Uber 28 Airbnb 22 Spotify 18
34.7K Views
High Frequency
~15 min Avg. Time
892 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