{ "data": { "question": { "questionId": "2821", "questionFrontendId": "2715", "boundTopicId": null, "title": "Timeout Cancellation", "titleSlug": "timeout-cancellation", "content": "

Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.

\n\n

After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked.

\n\n
\nsetTimeout(cancelFn, cancelTimeMs)\n
\n\n

Initially, the execution of the function fn should be delayed by t milliseconds.

\n\n

If, before the delay of t milliseconds, the function cancelFn is invoked, it should cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the specified delay t, fn should be executed with the provided args as arguments.

\n\n

 

\n

Example 1:

\n\n
\nInput: fn = (x) => x * 5, args = [2], t = 20\nOutput: [{"time": 20, "returned": 10}]\nExplanation: \nconst cancelTimeMs = 50;\nconst result = [];\n\nconst fn = (x) => x * 5;\n\nconst start = performance.now();\n\nconst log = (...argsArr) => {\n    const diff = Math.floor(performance.now() - start);\n    result.push({"time": diff, "returned": fn(...argsArr)});\n}\n     \nconst cancel = cancellable(log, [2], 20);\n\nconst maxT = Math.max(t, 50);\n          \nsetTimeout(cancel, cancelTimeMs);\n\nsetTimeout(() => {\n     console.log(result); // [{"time":20,"returned":10}]\n}, maxT + 15);\n\nThe cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms.\n
\n\n

Example 2:

\n\n
\nInput: fn = (x) => x**2, args = [2], t = 100\nOutput: []\nExplanation: \nconst cancelTimeMs = 50;\nThe cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called.\n
\n\n

Example 3:

\n\n
\nInput: fn = (x1, x2) => x1 * x2, args = [2,4], t = 30\nOutput: [{"time": 30, "returned": 8}]\nExplanation: \nconst cancelTimeMs = 100;\nThe cancellation was scheduled to occur after a delay of cancelTimeMs (100ms), which happened after the execution of fn(2,4) at 30ms.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Easy", "likes": 155, "dislikes": 173, "isLiked": null, "similarQuestions": "[]", "exampleTestcases": "(x) => x * 5\n[2]\n20\n50\n(x) => x**2\n[2]\n100\n50\n(x1, x2) => x1 * x2\n[2,4]\n30\n100", "categoryTitle": "JavaScript", "contributors": [], "topicTags": [], "companyTagStats": null, "codeSnippets": [ { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {Function} fn\n * @param {Array} args\n * @param {number} t\n * @return {Function}\n */\nvar cancellable = function(fn, args, t) {\n \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 */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };\ntype Fn = (...args: JSONValue[]) => void\n\nfunction cancellable(fn: Fn, args: JSONValue[], t: number): Function {\n\t\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 */", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"19.9K\", \"totalSubmission\": \"22.8K\", \"totalAcceptedRaw\": 19879, \"totalSubmissionRaw\": 22764, \"acRate\": \"87.3%\"}", "hints": [], "solution": { "id": "1974", "canSeeDetail": true, "paidOnly": false, "hasVideoSolution": false, "paidOnlyVideo": true, "__typename": "ArticleNode" }, "status": null, "sampleTestCase": "(x) => x * 5\n[2]\n20\n50", "metaData": "{\n \"name\": \"cancellable\",\n \"params\": [\n {\n \"name\": \"fn\",\n \"type\": \"string\"\n },\n {\n \"type\": \"string\",\n \"name\": \"args\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"t\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"cancelTimeMs\"\n }\n ],\n \"return\": {\n \"type\": \"integer\"\n },\n \"languages\": [\n \"javascript\",\n \"typescript\"\n ],\n \"manual\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": false, "envInfo": "{\"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.

\"], \"typescript\": [\"Typescript\", \"

TypeScript 5.1.6, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2022 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }