Problem Description
You are given a function fn, an array of arguments args, and an interval time t (in milliseconds). The function fn should be called immediately with args and then repeatedly every t milliseconds. A cancel function cancelFn is returned, and when cancelFn is eventually invoked (for example, via setTimeout(cancelFn, cancelTimeMs)), the repeated execution of fn stops.
Key Insights
- The initial call to fn happens immediately.
- Subsequent calls happen at a fixed interval t until cancellation.
- A cancellation mechanism is needed to stop future scheduled calls.
- In different languages, this is typically achieved using functions like setInterval/clearInterval (JavaScript) or background threads/timers (Python, C++, Java).
Space and Time Complexity
Time Complexity: O(1) per invocation (ignoring the repeated periodic timer, which is an asynchronous scheduling mechanism).
Space Complexity: O(1) aside from the overhead of the timer or thread handling the periodic calls.
Solution
We create a mechanism that immediately calls fn with the provided args, then starts a periodic scheduler that repeatedly invokes fn every t milliseconds. The scheduler runs asynchronously (using setInterval in JavaScript, a background thread in Python, etc.). A cancel function is returned that, when called, stops the scheduler. An important point is to ensure that the cancel mechanism correctly stops the scheduling to avoid additional unnecessary calls or resource leaks.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java.