Problem Description
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. The function fn
should be called with args
immediately and then called again every t
milliseconds until cancelFn
is called at cancelTimeMs
ms.
Key Insights
- The function needs to execute immediately and then repeatedly at a specified interval.
- A cancellation mechanism must be implemented via a timeout.
- The arguments for the function are dynamic and passed as an array.
- We need to ensure that the repeated calls do not exceed the cancellation time.
Space and Time Complexity
Time Complexity: O(n), where n is the number of calls made until cancellation. Space Complexity: O(1), as we are not using any additional data structures that grow with input size.
Solution
To solve this problem, we will use a combination of setTimeout
and setInterval
. The setTimeout
will manage the cancellation of the repeated function calls after a given time has elapsed. The setInterval
will be used to repeatedly call the provided function fn
at the specified interval t
.
- Immediately call the function
fn
with the providedargs
and store its result. - Set up a
setInterval
to callfn
withargs
everyt
milliseconds. - Use
setTimeout
to create a cancellation function that will clear the interval aftercancelTimeMs
milliseconds. - Return the cancel function.