{
"data": {
"question": {
"questionId": "2862",
"questionFrontendId": "2725",
"boundTopicId": null,
"title": "Interval Cancellation",
"titleSlug": "interval-cancellation",
"content": "Given a function fn,
an array of arguments args
, and an interval time t
, return a cancel function cancelFn
. The function fn
should be called with args
immediately and then called again every t
milliseconds until cancelFn
is called.\n
\n
Example 1:
\n\n\nInput: fn = (x) => x * 2, args = [4], t = 20, cancelT = 110\nOutput: \n[\n {"time": 0, "returned": 8},\n {"time": 20, "returned": 8},\n {"time": 40, "returned": 8},\n {"time": 60, "returned": 8},\n {"time": 80, "returned": 8},\n {"time": 100, "returned": 8}\n]\nExplanation: Every 20ms, fn(4) is called. Until t=110ms, then it is cancelled.\n\nconst cancel = cancellable(x => x * 2, [4], 20);\nsetTimeout(cancel, 110);\n\n1st fn call is at 0ms. fn(4) returns 8.\n2nd fn call is at 20ms. fn(4) returns 8.\n3rd fn call is at 40ms. fn(4) returns 8.\n4th fn call is at 60ms. fn(4) returns 8.\n5th fn call is at 80ms. fn(4) returns 8.\n6th fn call is at 100ms. fn(4) returns 8.\n\n\n
Example 2:
\n\n\nInput: fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 25, cancelT = 140\nOutput: \n[\n {"time": 0, "returned": 10},\n {"time": 25, "returned": 10},\n {"time": 50, "returned": 10},\n {"time": 75, "returned": 10},\n {"time": 100, "returned": 10},\n {"time": 125, "returned": 10}\n]\nExplanation: Every 25ms, fn(2, 5) is called. Until t=140ms, then it is cancelled.\n1st fn call is at 0ms \n2nd fn call is at 25ms \n3rd fn call is at 50ms \n4th fn call is at 75ms \n5th fn call is at 100ms \n6th fn call is at 125ms\nCancelled at 140ms\n\n\n
Example 3:
\n\n\nInput: fn = (x1, x2, x3) => (x1 + x2 + x3), args = [5, 1, 3], t = 50, cancelT = 180\nOutput: \n[\n {"time": 0, "returned": 9},\n {"time": 50, "returned": 9},\n {"time": 100, "returned": 9},\n {"time": 150, "returned": 9}\n]\nExplanation: Every 50ms, fn(5, 1, 3) is called. Until t=180ms, then it is cancelled. \n1st fn call is at 0ms\n2nd fn call is at 50ms\n3rd fn call is at 100ms\n4th fn call is at 150ms\nCancelled at 180ms\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 4.5.4, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2020 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }