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

Interval Cancellation

Difficulty: Easy


Problem Description

Given a function fn, an array of arguments args, and an interval time t, return a cancel function cancelFn. After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked. The function fn should be called with args immediately and then called again every t milliseconds until cancelFn is called at cancelTimeMs ms.


Key Insights

  • The function needs to execute immediately and then repeatedly at a specified interval.
  • A cancellation mechanism must be implemented via a timeout.
  • The arguments for the function are dynamic and passed as an array.
  • We need to ensure that the repeated calls do not exceed the cancellation time.

Space and Time Complexity

Time Complexity: O(n), where n is the number of calls made until cancellation. Space Complexity: O(1), as we are not using any additional data structures that grow with input size.


Solution

To solve this problem, we will use a combination of setTimeout and setInterval. The setTimeout will manage the cancellation of the repeated function calls after a given time has elapsed. The setInterval will be used to repeatedly call the provided function fn at the specified interval t.

  1. Immediately call the function fn with the provided args and store its result.
  2. Set up a setInterval to call fn with args every t milliseconds.
  3. Use setTimeout to create a cancellation function that will clear the interval after cancelTimeMs milliseconds.
  4. Return the cancel function.

Code Solutions

function cancellable(fn, args, t) {
    const results = [];
    // Immediately call the function and store the result
    results.push({ time: 0, returned: fn(...args) });
    
    // Set up the interval to call the function every t milliseconds
    const intervalId = setInterval(() => {
        results.push({ time: results.length * t, returned: fn(...args) });
    }, t);
    
    // Return the cancel function
    const cancelFn = () => {
        clearInterval(intervalId);
        return results; // Return the results collected
    };
    
    return cancelFn;
}
← Back to All Questions