2715. Timeout 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 []
/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
var cancellable = function(fn, args, t) {
    // Schedule the function to run after 't' milliseconds
    const timeoutId = setTimeout(() => {
        fn(...args);
    }, t);
    
    // Return a cancellation function that clears the timeout
    return function cancel() {
        clearTimeout(timeoutId);
    };
};

/**
 * Example usage:
 */
const result = [];
const fn = (x) => x * 5;
const args = [2], t = 20, cancelTimeMs = 50;

const start = performance.now();

// Log function that records time and function output
const log = (...argsArr) => {
    const diff = Math.floor(performance.now() - start);
    result.push({"time": diff, "returned": fn(...argsArr)});
}

// Create a cancellable function
const cancel = cancellable(log, args, t);

// Cancel the function before it executes
setTimeout(cancel, cancelTimeMs);

// After the max time, log the result
const maxT = Math.max(t, cancelTimeMs);
setTimeout(() => {
    console.log(result); // Expected: [{"time": 20, "returned": 10}]
}, maxT + 15);

```
['JavaScript']