{ "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
.
After a delay of t
, fn
should be called with args
passed as parameters unless cancelFn
was invoked before the delay of t
milliseconds elapses, specifically at cancelT
ms. In that case, fn
should never be called.
\n
Example 1:
\n\n\nInput: fn = (x) => x * 5, args = [2], t = 20, cancelT = 50\nOutput: [{"time": 20, "returned": 10}]\nExplanation: \nconst cancel = cancellable((x) => x * 5, [2], 20); // fn(2) called at t=20ms\nsetTimeout(cancel, 50);\n\nThe cancellation was scheduled to occur after a delay of cancelT (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, cancelT = 50 \nOutput: []\nExplanation: \nconst cancel = cancellable((x) => x**2, [2], 100); // fn(2) not called\nsetTimeout(cancel, 50);\n\nThe cancellation was scheduled to occur after a delay of cancelT (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, cancelT = 100\nOutput: [{"time": 30, "returned": 8}]\nExplanation:\nconst cancel = cancellable((x1, x2) => x1 * x2, [2,4], 30); // fn(2,4) called at t=30ms\nsetTimeout(cancel, 100);\n\nThe cancellation was scheduled to occur after a delay of cancelT (100ms), which happened after the execution of fn(2,4) at 30ms.\n\n\n
\n
Constraints:
\n\nfn is a function
args is a valid JSON array
1 <= args.length <= 10
20 <= t <= 1000
10 <= cancelT <= 1000
Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor 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
.
Your code is run with --harmony
flag, enabling new ES2022 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }