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 []
function cancellable(fn, args, t) {
    let timeoutId;  // To store the setTimeout reference
    let cancelFn;   // The cancel function to be returned

    // cancelFn will cancel the scheduled function call
    cancelFn = function () {
        clearTimeout(timeoutId);  // Cancel the timeout
    };

    // Set the function execution to be delayed by 't' milliseconds
    timeoutId = setTimeout(() => {
        fn(...args);  // Execute the function with the provided arguments
    }, t);

    // Return the cancel function
    return cancelFn;
}

// Example usage:

// Test 1
const cancelTimeMs = 50;
const cancelFn1 = cancellable((x) => {
    console.log("fn executed:", x * 5);
}, [2], 20);
setTimeout(cancelFn1, cancelTimeMs);  // Cancel after 50ms

// Test 2
const cancelFn2 = cancellable((x) => {
    console.log("fn executed:", x ** 2);
}, [2], 100);
setTimeout(cancelFn2, cancelTimeMs);  // Cancel after 50ms

// Test 3
const cancelFn3 = cancellable((x1, x2) => {
    console.log("fn executed:", x1 * x2);
}, [2, 4], 30);
setTimeout(cancelFn3, 100);  // Cancel after 100ms

```
['JavaScript']