Promise Time Limit
Write timeLimit(fn, t). It returns a new function that takes the same arguments as fn and behaves identically, except that if fn has not settled within t milliseconds the returned promise rejects with the string "Time Limit Exceeded".
Examples
const limited = timeLimit(async (n) => {
await new Promise((r) => setTimeout(r, 100));
return n * 2;
}, 50);
limited(5).catch(console.log);"Time Limit Exceeded"Constraints
- 0 <= t <= 1000
- fn returns a promise
Notes
- A rejection from fn itself must pass through unchanged rather than becoming a timeout.
- Clear the timer once the race settles, either way.
Hints
Promise Time Limit (reference solution)
One way to do it. The Editorial tab walks through why it is written this way.
Solution
1function timeLimit(fn, t) {
2 return function (...args) {
3 return new Promise((resolve, reject) => {
4 const timer = setTimeout(() => reject('Time Limit Exceeded'), t);
5 fn.apply(this, args).then(resolve, reject).finally(() => clearTimeout(timer));
6 });
7 };
8}Editorial: Promise Time Limit
Racing a timer
Every network call needs a deadline. Without one a hung request leaves a spinner on screen forever, because a promise that never settles never rejects either.
Approach
Two things are racing: the real call, and a timer that rejects. Promise.race says exactly that — whichever settles first wins, and the loser is ignored because a promise settles only once.
Implementation
function timeLimit(fn, t) { return function (...args) { return new Promise((resolve, reject) => { const timer = setTimeout(() => reject('Time Limit Exceeded'), t); fn.apply(this, args).then(resolve, reject).finally(() => clearTimeout(timer)); }); }; }
Worth knowing
timeLimit returns a function, not a promise. Nothing starts until that function is called, which is what lets you wrap once and reuse.
Clearing the timer in finally matters more than it looks: a pending timer keeps the event loop alive and, in Node, delays process exit. It also means a rejection from fn itself passes straight through rather than being replaced by a timeout.