2715. Timeout Cancellation solution 🚀
IntuitionThe problem involves executing a function fn after a specified delay t, with the option to cancel the execution before the delay ends. This requires a
# Intuition
The problem involves executing a function fn after a specified delay t, with the option to cancel the execution before the delay ends. This requires a mechanism to schedule and potentially cancel the execution, which can be efficiently handled using JavaScript's setTimeout and clearTimeout functions. By storing the timer ID returned by setTimeout, we can later cancel the scheduled execution if needed.

# Approach
1 - Use setTimeout to schedule the execution of fn with the provided arguments args after t milliseconds.

2 - Store the timer ID returned by setTimeout.

3 - Define a cancelFn function that uses clearTimeout with the stored timer ID to cancel the execution.

4 - Return the cancelFn from the cancellable function, allowing the caller to cancel the scheduled execution if needed.



# Complexity
- Time complexity:
Both setting up a timeout with setTimeout and canceling it with clearTimeout are constant-time operations.

- Space complexity:
The space usage is constant as it involves storing only the timer ID and the minimal state required for function execution.
![upvote pls.png](https://assets.leetcode.com/users/images/d2d25737-0486-4221-807f-608467c6de0c_1735985509.4099817.png)


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

    return function cancelFn() {
        clearTimeout(timerId);
    };
};

/**
 *  const result = [];
 *
 *  const fn = (x) => x * 5;
 *  const args = [2], t = 20, cancelTimeMs = 50;
 *
 *  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);
 *
 *  const maxT = Math.max(t, cancelTimeMs);
 *           
 *  setTimeout(cancel, cancelTimeMs);
 *
 *  setTimeout(() => {
 *      console.log(result); // [{"time":20,"returned":10}]
 *  }, maxT + 15)
 */
```
['JavaScript']