NeetCode #955LC-2637EasyJavaScript
← Back to All Problems#955 · #2637 · Promise Time Limit(有时间限制的 Promise)
📌 Problem Statement & Constraints
Given an asynchronous function
fn and a time limit t in milliseconds, return a wrapper: if fn(...args) settles within t milliseconds return its result, otherwise reject with the string Time Limit Exceeded.💡 Core Algorithmic Approaches
- Race
fn(...args)against a Promise that rejects aftertmilliseconds. - Set a rejection timer with
setTimeout, and clear it whenfnsettles. - Clearing the timer is mandatory: otherwise it fires after
fnfinishes, leaving a dangling timer that may cause an unhandled rejection. - Arguments must be forwarded, and a rejection from the original Promise must be propagated.
💻 Benchmark Python3 Implementation
var timeLimit = function(fn, t) {
return async function(...args) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject("Time Limit Exceeded"), t);
fn(...args).then(
value => { clearTimeout(timer); resolve(value); },
err => { clearTimeout(timer); reject(err); }
);
});
};
};⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1) besides the cost of fn itself.
💾 Space Complexity
O(1): one timer.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting
clearTimeout: afterfnfinishes on time the timer still fires and rejects an already-settled Promise. - Using
Promise.racewithout clearing the timer: the same dangling-timer problem remains. - Expecting
fnto be cancelled on timeout: JavaScript cannot forcibly cancel a Promise; its result is simply ignored. - Rejecting with an
Errorobject: the problem requires the exact stringTime Limit Exceeded.