2715.Leetcode- Timeout Cancellation Solution
IntuitionThis problem is about asynchronous execution control, specifically handling timeouts and cancellations. In JavaScript, we use setTimeout to schedule fu
# **Intuition**  

This problem is about **asynchronous execution control**, specifically handling **timeouts and cancellations**. In JavaScript, we use `setTimeout` to schedule function execution, but we also need a way to **cancel** it before execution if required.  

By returning a **cancellation function**, we allow users to clear the timeout before it executes. This is useful in scenarios like:  
✅ **Debouncing input fields**  
✅ **Cancelling API calls**  
✅ **Optimizing event listeners**  

---

# **Understanding `setTimeout` & Cancellation**  

✅ **What is `setTimeout`?**  
`setTimeout` is a built-in JavaScript function used to delay function execution for a specified time (in milliseconds).  

✅ **How to Cancel a Timeout?**  
We use `clearTimeout(timeoutID)`, where `timeoutID` is the value returned by `setTimeout`. This prevents the function from running if the timeout is cleared before execution.  

---

# **Approach**  

I explored **two different approaches** to solve this problem:  

---

# 🔹 **Approach 1: Using `setTimeout` with Explicit Clear**  

```js
var cancellable = function(fn, args, t) {
    let timer = setTimeout(() => {
        fn(...args);
    }, t);

    return () => {
        clearTimeout(timer);
    };
};
```

📌 **Explanation:**  
- `setTimeout` schedules function execution after `t` milliseconds.  
- The returned function (`cancellable`) stores the timeout reference.  
- If the user calls this function, `clearTimeout(timer)` cancels execution.  

✅ **Pros:**  
- Simple and easy to understand.  
- Works well for basic timeout cancellations.  

---

# 🔹 **Approach 2: Passing Arguments Directly to `setTimeout`**  

```js
var cancellable = function(fn, args, t) {
    let timer = setTimeout(fn, t, ...args);
    return () => clearTimeout(timer);
};
```

📌 **Key Differences:**  
- Instead of using an arrow function inside `setTimeout`, we pass `fn` directly with arguments.  
- Reduces function wrapping overhead, making it slightly more efficient.  

✅ **Pros:**  
- More concise than Approach 1.  
- Uses **native `setTimeout` argument passing**, which improves readability.  

---

# **Complexity Analysis**  

- **Time Complexity:**  
  - $$O(1)$$ – `setTimeout` and `clearTimeout` are constant-time operations.  

- **Space Complexity:**  
  - $$O(1)$$ – We store only a single timeout reference.  

---

# **Code Implementation**  

```js
/**
 * @param {Function} fn
 * @param {Array} args
 * @param {number} t
 * @return {Function}
 */
var cancellable = function(fn, args, t) {
    let timer = setTimeout(fn, t, ...args);
    return () => clearTimeout(timer);
};

/**
 *  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);
 */
```

---

# **Important Topics to Learn 📚**  

- **JavaScript Timers (`setTimeout`, `clearTimeout`)**: Controlling function execution timing.  
- **Asynchronous Execution**: Handling delayed execution in JavaScript.  
- **Function Closures**: Returning functions with access to outer variables.  
- **Higher-Order Functions**: Functions that return other functions (like our cancellable function).  

---

# 🚀 **Support & Feedback**  

✅ If you found this helpful, **please upvote & comment** on my solution!  
💬 Let’s discuss alternative solutions & improvements! 🚀
['JavaScript']