[Easy] LeetCode JS 30 - 2725. Interval Cancellation
March 5, 2024
LeetCode 30 Days of JavaScript
This question is from LeetCode's 30 Days of JavaScript Challenge
2725. Interval CancellationQuestion Prompt
Given a function fn
, an array of arguments args
, and an interval time t
, return a cancel function cancelFn
.
After a delay of cancelTimeMs
, the returned cancel function cancelFn
will be invoked.
setTimeout(cancelFn, cancelTimeMs)
The function fn
should be called with args
immediately and then called again every t
milliseconds until cancelFn
is called at cancelTimeMs
ms.
Input: fn = (x) => x * 2, args = [4], t = 35
Output:
[
{"time": 0, "returned": 8},
{"time": 35, "returned": 8},
{"time": 70, "returned": 8},
{"time": 105, "returned": 8},
{"time": 140, "returned": 8},
{"time": 175, "returned": 8}
]
Explanation:
const cancelTimeMs = 190;
const cancelFn = cancellable((x) => x * 2, [4], 35);
setTimeout(cancelFn, cancelTimeMs);
Every 35ms, fn(4) is called. Until t=190ms, then it is cancelled.
1st fn call is at 0ms. fn(4) returns 8.
2nd fn call is at 35ms. fn(4) returns 8.
3rd fn call is at 70ms. fn(4) returns 8.
4th fn call is at 105ms. fn(4) returns 8.
5th fn call is at 140ms. fn(4) returns 8.
6th fn call is at 175ms. fn(4) returns 8.
Cancelled at 190ms
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
First, create a function named cancellable
that takes in fn
, args
, and t
. Within the function, we need to call fn
with ...args
first as the question requires.
Then, the core of the repetition logic lies in JavaScript's setInterval
function. It takes the provided function (fn
) and the interval (t
) and schedules its repeated execution. The setInterval
function returns an interval ID, which is stored in the intervalId
variable. This ID is crucial for later cancellation.
The cancellable
function returns another function. This inner function is responsible for clearing the repetition when invoked. It uses clearInterval
and the stored intervalId
to halt the scheduled executions.
var cancellable = function (fn, args, t) {
fn(...args);
const intervalId = setInterval(() => {
fn(...args);
}, t);
return function cancelFn() {
clearInterval(intervalId);
};
};