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

  1. Race fn(...args) against a Promise that rejects after t milliseconds.
  2. Set a rejection timer with setTimeout, and clear it when fn settles.
  3. Clearing the timer is mandatory: otherwise it fires after fn finishes, leaving a dangling timer that may cause an unhandled rejection.
  4. 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: after fn finishes on time the timer still fires and rejects an already-settled Promise.
  • Using Promise.race without clearing the timer: the same dangling-timer problem remains.
  • Expecting fn to be cancelled on timeout: JavaScript cannot forcibly cancel a Promise; its result is simply ignored.
  • Rejecting with an Error object: the problem requires the exact string Time Limit Exceeded.