2821. Timeout Cancellation
My accepted JavaScript solution to LeetCode problem 2821, Timeout Cancellation, running in 72ms.
- Difficulty: Easy
- JavaScript
- Runtime 72ms
- Memory 53.2MB
- 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 72ms, memory 53.2MB, accepted 2025-12-31.
/**
* @param {Function} fn
* @param {Array} args
* @param {number} t
* @return {Function}
*/
var cancellable = function(fn, args, t) {
const timeoutId = setTimeout(() => fn(...args), t);
return function cancelFn() {
clearTimeout(timeoutId);
};
};
/**
* const result = [];
*
* const fn = (x) => x * 5;
* const args = [2], t = 20, cancelTimeMs = 50;
*
* const start = performance.now();
*
* const log = (...argsArr) => {
* const diff = Math.floor(performance.now() - start);
* result.push({"time": diff, "returned": argsArr[0]});
* }
*
* const cancel = cancellable((x) => { log(x * 5); }, args, t);
*
* const maxT = Math.max(t, cancelTimeMs);
*
* setTimeout(cancel, cancelTimeMs);
*
* setTimeout(() => {
* console.log(result); // [{"time":20,"returned":10}]
* }, maxT + 15)
*/