Interval Cancellation
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```javascript []
function cancellable(fn, args, t) {
  let intervalId;

  // Immediately invoke the function and store the result.
  console.log({ time: 0, returned: fn(...args) });

  // Schedule repeated execution every t milliseconds.
  let startTime = Date.now();
  intervalId = setInterval(() => {
    const elapsedTime = Date.now() - startTime;
    console.log({ time: elapsedTime, returned: fn(...args) });
  }, t);

  // Return a cancel function to stop the execution.
  return () => clearInterval(intervalId);
}

// Example Usage 1
const cancelTimeMs1 = 190;
const cancelFn1 = cancellable((x) => x * 2, [4], 35);
setTimeout(cancelFn1, cancelTimeMs1);

// Example Usage 2
const cancelTimeMs2 = 165;
const cancelFn2 = cancellable((x1, x2) => x1 * x2, [2, 5], 30);
setTimeout(cancelFn2, cancelTimeMs2);

// Example Usage 3
const cancelTimeMs3 = 180;
const cancelFn3 = cancellable((x1, x2, x3) => x1 + x2 + x3, [5, 1, 3], 50);
setTimeout(cancelFn3, cancelTimeMs3);

```
['JavaScript']