Interval Cancellation
IntuitionThe problem requires creating a function that repeatedly invokes another function at specified intervals and allows the repetition to be canceled after
# Intuition
The problem requires creating a function that repeatedly invokes another function at specified intervals and allows the repetition to be canceled after a given delay. The key is to call the function immediately and then use setInterval to keep invoking it at regular intervals until the cancel function is called.

# Approach
1. Define a cancellable function that takes fn, args, and t as input parameters.

2. Immediately call fn with the provided args.

3. Use setInterval to repeatedly call fn at every t milliseconds.

4. Create a cancel function that uses clearInterval to stop the repeated invocations.

5. Return the cancel function to allow external cancellation of the interval.

# Complexity
- Time complexity:
    $$O(1)$$
Both setting up and clearing intervals are constant-time operations.

- Space complexity:
    $$O(1)$$
The space complexity is constant since we are only using a fixed number of variables.

# Code
```javascript []
/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
var cancellable = function(fn, args, t) {
    fn(...args);
    const intervalId = setInterval(() => {
        fn(...args);
    }, t);
    return () => clearInterval(intervalId);
};


   const result = [];
 
   const fn = (x) => x * 2;
   const args = [4], t = 35, cancelTimeMs = 190;
 
   const start = performance.now();
 
   const log = (...argsArr) => {
       const diff = Math.floor(performance.now() - start);
       result.push({"time": diff, "returned": fn(...argsArr)});
   }
        
   const cancel = cancellable(log, args, t);
 
   setTimeout(cancel, cancelTimeMs);
    
   setTimeout(() => {
       console.log(result); // [
                            //     {"time":0,"returned":8},
                            //     {"time":35,"returned":8},
                           //     {"time":70,"returned":8},
                           //     {"time":105,"returned":8},
                           //     {"time":140,"returned":8},
                           //     {"time":175,"returned":8}
                           // ]
  }, cancelTimeMs + t + 15)    
 
```
['JavaScript']