-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathPromiseTimeLimit.js
More file actions
30 lines (28 loc) · 845 Bytes
/
PromiseTimeLimit.js
File metadata and controls
30 lines (28 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
var timeLimit = function (fn, t) {
return async function (...args) {
return new Promise((delayresolve, reject) => {
const timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
reject("Time Limit Exceeded");
}, t);
fn(...args)
.then((result) => {
clearTimeout(timeoutId);
delayresolve(result);
})
.catch((error) => {
clearTimeout(timeoutId);
reject(error);
});
});
};
};
/**
* const limited = timeLimit((t) => new Promise(res => setTimeout(res, t)), 100);
* limited(150).catch(console.log) // "Time Limit Exceeded" at t=100ms
*/