Problem Description
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. Initially, the execution of the function fn should be delayed by t milliseconds. If, before the delay of t milliseconds, the function cancelFn is invoked, it should cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the specified delay t, fn should be executed with the provided args as arguments.
Key Insights
- The function execution is delayed by a specified amount of time (t ms).
- A cancel function is provided that, if invoked before the delay, prevents the execution of the original function.
- If the cancel function is not invoked within the delay, the original function is executed with the provided arguments.
- The behavior of both the delayed execution and cancellation is managed using JavaScript's setTimeout.
Space and Time Complexity
Time Complexity: O(1) for the cancel function, O(t) for the function execution if not canceled.
Space Complexity: O(1) as we are not using any additional data structures that scale with input size.
Solution
The solution involves using a closure to encapsulate the state related to the function execution and its cancellation. We utilize setTimeout to delay the execution of the function and to schedule the cancellation. The cancel function clears the timeout if it's called before the function execution. If the timeout completes without cancellation, the function is executed with the provided arguments.