LeetCode Problem Workspace
Interval Cancellation
Implement a cancellable function with repeated executions at fixed intervals before a cancellation time.
0
Topics
1
Code langs
0
Related
Practice Focus
Easy · Interval Cancellation core interview pattern
Answer-first summary
Implement a cancellable function with repeated executions at fixed intervals before a cancellation time.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Interval Cancellation core interview pattern
To solve the Interval Cancellation problem, you need to create a function that calls another function at regular intervals, and stops once a cancellation time is reached. The main challenge is ensuring that the function runs repeatedly and can be stopped at the specified time.
Problem Statement
Given a function fn, an array of arguments args, and a cancellation time cancelTimeMs, return a cancel function cancelFn that calls fn with args immediately and then repeats the call every t milliseconds. The function should continue calling fn until the cancellation time cancelTimeMs is reached.
The goal is to simulate repeated execution of a function, ensuring the cancel function halts further calls after a specified delay. The function should be invoked multiple times, and you should correctly implement the cancellation mechanism with the specified intervals.
Examples
Example 1
Input: See original problem statement.
Output: See original problem statement.
setTimeout(cancelFn, cancelTimeMs)
Example 2
Input: fn = (x) => x * 2, args = [4], t = 35
Output: [ {"time": 0, "returned": 8}, {"time": 35, "returned": 8}, {"time": 70, "returned": 8}, {"time": 105, "returned": 8}, {"time": 140, "returned": 8}, {"time": 175, "returned": 8} ]
const cancelTimeMs = 190; const cancelFn = cancellable((x) => x * 2, [4], 35); setTimeout(cancelFn, cancelTimeMs);
Every 35ms, fn(4) is called. Until t=190ms, then it is cancelled. 1st fn call is at 0ms. fn(4) returns 8. 2nd fn call is at 35ms. fn(4) returns 8. 3rd fn call is at 70ms. fn(4) returns 8. 4th fn call is at 105ms. fn(4) returns 8. 5th fn call is at 140ms. fn(4) returns 8. 6th fn call is at 175ms. fn(4) returns 8. Cancelled at 190ms
Example 3
Input: fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 30
Output: [ {"time": 0, "returned": 10}, {"time": 30, "returned": 10}, {"time": 60, "returned": 10}, {"time": 90, "returned": 10}, {"time": 120, "returned": 10}, {"time": 150, "returned": 10} ]
const cancelTimeMs = 165; const cancelFn = cancellable((x1, x2) => (x1 * x2), [2, 5], 30) setTimeout(cancelFn, cancelTimeMs)
Every 30ms, fn(2, 5) is called. Until t=165ms, then it is cancelled. 1st fn call is at 0ms 2nd fn call is at 30ms 3rd fn call is at 60ms 4th fn call is at 90ms 5th fn call is at 120ms 6th fn call is at 150ms Cancelled at 165ms
Constraints
- fn is a function
- args is a valid JSON array
- 1 <= args.length <= 10
- 30 <= t <= 100
- 10 <= cancelTimeMs <= 500
Solution Approach
Immediate and Repeated Execution
Start by executing the function fn immediately with the provided arguments args. Then, repeatedly call fn every t milliseconds using setInterval. This ensures that the function runs at regular intervals.
Handling Cancellation
Use setTimeout to schedule the cancellation function cancelFn to be triggered after cancelTimeMs milliseconds. This will stop the repeated executions by clearing the interval, ensuring the function stops after the given delay.
Return the Cancel Function
The final cancelFn should be returned, allowing for easy cancellation of the repeated executions. Ensure that cancelFn can be invoked at any point to stop the interval and cancel further function calls.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | ** |
| Space | ** |
Time complexity is dominated by the interval calls, where each interval is triggered once every t milliseconds until cancellation. Space complexity is constant, as we're only maintaining a reference to the set interval and the cancel function.
What Interviewers Usually Probe
- Look for correct handling of repeated execution and cancellation at the right moment.
- Watch for the proper use of
setIntervalfor periodic execution andsetTimeoutfor cancellation. - Ensure that the solution works even for the edge cases involving small or large values for
tandcancelTimeMs.
Common Pitfalls or Variants
Common pitfalls
- Failing to clear the interval properly can cause the function to continue executing beyond the cancellation time.
- Not accounting for edge cases where the cancellation time is too short for multiple executions.
- Incorrect handling of the cancel function could lead to premature or delayed cancellation of the repeated function calls.
Follow-up variants
- Modify the function to allow multiple functions to be cancelled in sequence.
- Introduce a delay before starting the repeated function calls, not just an immediate execution.
- Add support for dynamic changes to the interval time during execution.
FAQ
What is the core pattern behind the Interval Cancellation problem?
The problem focuses on managing a function that repeats execution at fixed intervals and includes the ability to cancel it after a given time, using setInterval and setTimeout.
How do I stop the function from running after a specified time?
You can stop the function by using setTimeout to invoke the cancel function, which will clear the interval set by setInterval.
What is the role of the cancelFn function in the problem?
The cancelFn function stops the repeated executions by clearing the interval once the cancellation time is reached.
Why is it important to cancel the function after a set time in this problem?
The cancellation ensures that the function doesn't run indefinitely, allowing you to control how long the repeated execution lasts, which is essential for proper resource management and accurate timing.
How does this problem relate to interval-based scheduling in other contexts?
This problem illustrates the core concept of scheduling tasks at fixed intervals and providing a mechanism for terminating them, which is common in many event-driven programming scenarios.
Solution
Solution 1
#### TypeScript
function cancellable(fn: Function, args: any[], t: number): Function {
fn(...args);
const time = setInterval(() => fn(...args), t);
return () => clearInterval(time);
}
/**
* const result = []
*
* const fn = (x) => x * 2
* const args = [4], t = 20, cancelT = 110
*
* const log = (...argsArr) => {
* result.push(fn(...argsArr))
* }
*
* const cancel = cancellable(fn, args, t);
*
* setTimeout(() => {
* cancel()
* console.log(result) // [
* // {"time":0,"returned":8},
* // {"time":20,"returned":8},
* // {"time":40,"returned":8},
* // {"time":60,"returned":8},
* // {"time":80,"returned":8},
* // {"time":100,"returned":8}
* // ]
* }, cancelT)
*/