Given an asynchronous function fn and a time limit t (in milliseconds), return a time-limited version of the function.
The fn will accept parameters for the time-limited function. This time-limited function should meet the following conditions:
fn completes within the time limit of t milliseconds, the time-limited function should resolve to the result of fn .fn exceeds the time limit, the time-limited function should reject and return the string "Time Limit Exceeded".// Example
Input:
fn = async (n) => {
await new Promise(res => setTimeout(res, 100));
return n * n;
}
inputs = [5]
t = 50
Output: {"rejected":"Time Limit Exceeded","time":50}
Explanation:
const limited = timeLimit(fn, t)
const start = performance.now()
let result;
try {
const res = await limited(...inputs)
result = {"resolved": res, "time": Math.floor(performance.now() - start)};
} catch (err) {
result = {"rejected": err, "time": Math.floor(performance.now() - start)};
}
The original Promise resolves after 100 milliseconds,
but the time limit is 50 milliseconds,
so the Promise is rejected at t=50 milliseconds.
function promiseTimeLimit(fn, t) {
return function(...args){
const timeoutPromise = new Promise((resolve, reject)=>{
setTimeout(() => reject("Time Limit Exceeded"), t)
})
const funcPromise = fn(...args)
return Promise.race([timeoutPromise, funcPromise])
}
}
const testFn = async (n) => {
await new Promise(res => setTimeout(res, 100));
return n * n;
}
const timeLimit = promiseTimeLimit(testFn, 3000)
const res = await timeLimit(10)
console.log('res',res) // res 100