js Easy
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires creating a cancellable function, which executes after a delay unle
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires creating a cancellable function, which executes after a delay unless canceled. The intuition revolves around leveraging setTimeout for the delay and clearTimeout to cancel the execution.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitialize the Timer:\n\nUse setTimeout to schedule the execution of the provided function fn after t milliseconds with arguments args.\nReturn a Cancellation Function:\n\nUse clearTimeout within the cancellation function to stop the timer before fn executes.\nEnsure the Timer identifier is in the correct scope so the cancellation function can access and clear it.\nExecution Flow:\n\nCall fn(...args) after the delay t if not canceled.\nAllow cancellation of the timer by calling the returned function.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\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    const cancelfn =function(){\n        clearTimeout(Timer)\n    }\n    const Timer = setTimeout(()=>{\n        fn(...args)\n    },t)\n    \n    return cancelfn\n};\n\n/**\n *  const result = [];\n *\n *  const fn = (x) => x * 5;\n *  const args = [2], t = 20, cancelTimeMs = 50;\n *\n *  const start = performance.now();\n *\n *  const log = (...argsArr) => {\n *      const diff = Math.floor(performance.now() - start);\n *      result.push({"time": diff, "returned": fn(...argsArr)});\n *  }\n *       \n *  const cancel = cancellable(log, args, t);\n *\n *  const maxT = Math.max(t, cancelTimeMs);\n *           \n *  setTimeout(cancel, cancelTimeMs);\n *\n *  setTimeout(() => {\n *      console.log(result); // [{"time":20,"returned":10}]\n *  }, maxT + 15)\n */\n```
['JavaScript']