2715. Timeout Cancellation
On this page, we explore LeetCode Problem 2715: Timeout Cancellation. This problem involves delaying the execution of a function and providing a way to cancel it if needed.
📄 Problem Statement
Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn.
After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked:
setTimeout(cancelFn, cancelTimeMs);
Initially, the execution of the function fn should be delayed by t milliseconds. If cancelFn is invoked before t milliseconds, it should cancel the delayed execution of fn. Otherwise, fn should be executed with the provided args.
💡 Example
Input:
const fn = (x) => console.log(x);
const args = [42];
const t = 2000;
const cancelTimeMs = 1000;
const cancelFn = cancellable(fn, args, t);
setTimeout(cancelFn, cancelTimeMs);
Output: undefined (since fn was cancelled before execution)
🧠 Explanation
Use setTimeout to schedule fn(...args) to run after t milliseconds. Capture its timeout ID.
Then return a cancelFn function that clears the timeout using clearTimeout. If cancelFn is called before t ms, it will cancel the function from running.
✅ Your Solution
/**
* @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);
};
};