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
fncompletes within the time limit, return its result - โ If
fnexceeds 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
Visualization
Time & Space Complexity
Constant time setup, actual time depends on which promise resolves first
Only creates two promises and a timer reference
Constraints
- 1 โค t โค 104 (timeout in milliseconds)
-
The function
fnreturns a Promise -
The returned function should maintain the same signature as
fn - Time limit should be enforced precisely