2862. Interval Cancellation
My accepted JavaScript solution to LeetCode problem 2862, Interval Cancellation, running in 64ms.
- Difficulty: Easy
- JavaScript
- Runtime 64ms
- Memory 54.1MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
JavaScript
Accepted on LeetCode — runtime 64ms, memory 54.1MB, accepted 2025-12-31.
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function(fn, args, t) {
fn(...args); // Call immediately
const intervalId = setInterval(() => fn(...args), t);
return function cancelFn() {
clearInterval(intervalId);
};
};
/**
* const result = [];
*
* const fn = (x) => x * 2;
* const args = [4], t = 35, cancelTimeMs = 190;
*
* const start = performance.now();
*
* const log = (...argsArr) => {
* const diff = Math.floor(performance.now() - start);
* result.push({"time": diff, "returned": argsArr[0]});
* }
*
* const cancel = cancellable((...argsArr) => log(fn(...argsArr)), args, t);
*
* setTimeout(cancel, cancelTimeMs);
*
* setTimeout(() => {
* console.log(result);
* }, cancelTimeMs + t + 15)
*/