LeetCode 2715: Timeout Cancellation - JavaScript Solution 🚀 Easy explanation
IntuitionThe problem requires us to execute a function after a delay but also provides a way to cancel the execution if needed.To solve this, we can take advant
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires us to execute a function after a delay but also provides a way to cancel the execution if needed.

To solve this, we can take advantage of JavaScript’s **setTimeout()**, which schedules a function to run after a given time. However, we also need a way to stop it before it executes, which can be done using **clearTimeout()**.

💡 Think of it like setting an alarm⏰—if you turn it off before it rings, it never goes off!

# Approach
<!-- Describe your approach to solving the problem. -->
1. Use **setTimeout()** to delay the execution of fn by t milliseconds.
2. Store the timeout ID returned by **setTimeout()**.
3. Return a cancel function that, when called, will use **clearTimeout()** to prevent fn from running.
4. If cancelFn is called before t milliseconds, the function is never executed. Otherwise, it runs as scheduled.

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(1)$$ → We just schedule a timeout and cancel it if needed.

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(1)$$ → We only store the timeout ID.


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

    //running the function after the t(time)
    let cancelId = setTimeout(() => fn(...args),t);

    return function cancelFn(){
        //clearing out the time out 
        clearTimeout(cancelId);
    }
};

// An array to store the result of the function executions
   const result = [];
    
   const fn = (x) => x * 5;
   const args = [2], t = 20, cancelTimeMs = 50;

   // Recording the start time for performance measurement
   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)
```
# 💡 Key Takeaway: 
setTimeout allows delaying a function call, and clearTimeout helps prevent its execution if needed. This approach efficiently implements the timeout cancellation mechanism. 🚀
['JavaScript']