🗓️ LeetCoding Challenge JS Day 15 || ~ BEATS 90% ~! 🔥
IntuitionWe need to repeatedly call a function at a fixed time interval until we manually stop it. This is like setting an alarm that keeps ringing every few se
# Intuition
We need to repeatedly call a function at a fixed time interval until we manually stop it. This is like setting an alarm that keeps ringing every few seconds unless we turn it off.
# Approach
1. Call the function once immediately to ensure it runs right away.
2. Set up a loop using setTimeout, where the function calls itself again after t milliseconds.
3. Use a stop flag to control when the function should stop repeating.
4. Return a function that, when called, sets stop = true, preventing further executions.

# Complexity
- Time complexity:
If the function runs k times before being stopped, the complexity is O(k).

- Space complexity:
We only store a few variables (stop, fn, args, and t), so the space complexity is O(1).

# Code
```javascript []
var cancellable = function(fn, args, t) {
    let stop = false;
    fn(...args); // Call the function immediately

    const startTimer = () => {
        setTimeout(() => {
            if (stop) return;
            fn(...args);
            startTimer();
        }, t)
    }

   startTimer();

    const stopF = () => {
        stop = true;
    }

    return stopF;
};
```
['JavaScript']