Beat 95.55% User: Simple Approach
Intuition\nThe cancellable function is designed to create a function that cancels the execution of another function (fn) if it takes longer than a specified tim
# Intuition\nThe cancellable function is designed to create a function that cancels the execution of another function (fn) if it takes longer than a specified time (t). It uses a timer to achieve this. If the timer expires before fn completes, it will prevent the function from executing.\n\n# Approach\n1. The cancellable function takes three parameters:\n\nfn: The function to be executed.\nargs: An array of arguments to pass to the function fn.\nt: The time limit in milliseconds. If fn doesn\'t complete within this time, it will be canceled.\nInside the cancellable function:\n\n2. It sets up a timer using setTimeout that will execute fn(...args) after a delay of t milliseconds.\nIt returns a function that can be used to cancel the timer.\n3. The returned cancel function, when called, uses clearTimeout to cancel the execution of fn if it hasn\'t already started.\n\n# Complexity\n- Time complexity:\no(1)\n\n- Space complexity:\no(1)\n\n# Code\n```\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 timeOut = setTimeout(() => {\n        fn(...args)\n    },t)\n    return function(){\n        clearTimeout(timeOut)\n    }\n};\n\n/**\n *  const result = []\n *\n *  const fn = (x) => x * 5\n *  const args = [2], t = 20, cancelT = 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, cancelT)\n *           \n *  setTimeout(() => {\n *     cancel()\n *  }, cancelT)\n *\n *  setTimeout(() => {\n *     console.log(result) // [{"time":20,"returned":10}]\n *  }, maxT + 15)\n */\n\n\n```
['JavaScript']