We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Promise Time Limit

Difficulty: Medium


Problem Description

Given an asynchronous function fn and a time t in milliseconds, return a new time limited version of the input function. The time limited function should resolve with the result if fn completes within the time limit of t milliseconds, or reject with the string "Time Limit Exceeded" if the execution of fn exceeds the time limit.


Key Insights

  • The function needs to handle both the resolution and rejection of promises.
  • We can use Promise.race to implement the time limit by racing the execution of fn against a timeout promise.
  • Properly measuring the execution time is essential to ensure the function adheres to the specified limit.

Space and Time Complexity

Time Complexity: O(1) for setting up the promises, O(n) for the execution of the asynchronous function (where n is the execution time of fn).

Space Complexity: O(1) since we are only using a fixed number of variables regardless of the input size.


Solution

To solve the problem, we will create a new asynchronous function that wraps the original function fn. We'll use Promise.race to compete between the execution of fn and a timeout promise that rejects after t milliseconds. If fn resolves first, we return its result; if the timeout promise rejects first, we throw an error indicating that the time limit has been exceeded.


Code Solutions

function timeLimit(fn, t) {
    return async function(...args) {
        // Create a promise that rejects after `t` milliseconds
        const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => reject("Time Limit Exceeded"), t);
        });

        // Race the original function against the timeout
        return Promise.race([
            fn(...args),           // Call the original function
            timeoutPromise         // Timeout promise
        ]);
    };
}
← Back to All Questions