2725. Interval Cancellation
Intuition\nThe code appears to be implementing a cancellable function. The cancellable function takes three parameters: a function fn to be executed, an array o
# Intuition\nThe code appears to be implementing a cancellable function. The `cancellable` function takes three parameters: a function `fn` to be executed, an array of arguments `args` for that function, and a time interval `t` in milliseconds. The purpose is to execute the provided function at regular intervals and allow cancellation of this scheduled execution.\n\n# Approach\n1. The code initializes a `startTime` variable to track the starting time when the `cancellable` function is called.\n2. It defines an array `result` to store information about each invocation of the provided function, including the time elapsed since the start and the returned value.\n3. The `invokeFn` function is defined to execute the provided function with the specified arguments and record the time and return value.\n4. The `invokeFn` function is called once immediately when the `cancellable` function is invoked.\n5. A setInterval is set up to repeatedly call `invokeFn` at intervals of `t` milliseconds.\n6. The `cancelFn` function is defined to clear the interval, logging the cancellation time and the result array.\n7. The `cancelFn` function is returned, allowing the user to cancel the scheduled function executions.\n\n# Complexity\n- Time complexity: The time complexity depends on the number of invocations of the provided function. If the function runs indefinitely, the time complexity is unbounded. If it runs for a fixed duration, the time complexity is proportional to the number of invocations, which is determined by the time interval `t`.\n  \n- Space complexity: The space complexity is determined by the `result` array, which stores information about each invocation. The space complexity is proportional to the number of invocations, again depending on the time interval `t`. The rest of the variables have constant space complexity.\n\n# Code\n```javascript\n/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n\n    const startTime = Date.now();\n    const result = [];\n\n    const invokeFn = () => {\n        const currentTime = Date.now() - startTime;\n        const returnValue = fn(...args);\n        result.push({\n            time: currentTime,\n            returned: returnValue\n        });\n    }\n\n    invokeFn();\n    \n    const id = setInterval(invokeFn, t);\n\n    const cancelFn = () => {\n        clearInterval(id);\n        console.log(\'Cancelled at\', Date.now() - startTime, \'ms\');\n        console.log(result); // Optional: Log the result array when cancelled\n    }\n\n    return cancelFn;\n};\n```\n
['JavaScript']