Problem Description
Implement two functions: customInterval and customClearInterval. customInterval takes a function fn, a delay, and a period and repeatedly executes fn with intervals defined by the formula (delay + period * count), where count starts at 0 for the first call. customClearInterval stops any further executions when provided with the id returned from customInterval.
Key Insights
- Instead of using setInterval, use recursive scheduling with setTimeout (or equivalent in other languages).
- The delay for each execution increases linearly using the formula delay + period * count.
- Maintain a cancellation flag or reference so that scheduled future calls can be terminated.
Space and Time Complexity
Time Complexity: O(n) for n executions, where each timer callback runs in constant time. Space Complexity: O(1) additional space is needed for the cancellation flag and timer reference.
Solution
To solve the problem, we use a recursive scheduling method. In JavaScript, for example, we use setTimeout to schedule the next execution. On each execution, we first check if a cancellation flag is set; if not, we execute the provided function fn, increment the count, compute the next delay based on the formula, and then recursively schedule the next call. For cancellation with customClearInterval, we update the flag and clear the current timeout if necessary. Similar ideas can be applied in other languages using available timer/scheduling mechanisms, ensuring that each scheduled execution can be cancelled when needed.