Run a function with delays growing by delay + period * count
The task at hand involves creating a custom function named mySetInterval(func, delay, period) that diverges from the traditional window.setInterval behavior. Instead of executing the provided function func at regular intervals, this function should execute func with increasing delays following a linear pattern. The delay before each subsequent execution is calculated using the formula delay + period * count, where count is the number of times the function has been called. Compare this with the native setInterval(), which uses a fixed delay.
To illustrate, consider the following example:
let prev = Date.now();
const func = () => {
const now = Date.now();
console.log('Time elapsed:', now - prev, 'ms');
prev = now;
};
const id = mySetInterval(func, 100, 200);
// Output:
// Time elapsed: 100ms
// Time elapsed: 400ms (100 + 200 * 1)
// Time elapsed: 900ms (100 + 200 * 2)
// Time elapsed: 1600ms (100 + 200 * 3)
// ...
This functionality allows for scheduling tasks with increasing intervals, which can be particularly useful in scenarios where the intensity of task execution needs to decrease over time.
Additionally, a function named myClearInterval(id) should be provided to stop the scheduled execution. This function should take an identifier returned by mySetInterval and cancel the scheduled task.
The challenge lies not only in implementing the increasing delay logic but also in ensuring that the mySetInterval and myClearInterval functions can be used similarly to their native JavaScript counterparts, providing a seamless interface for scheduling and canceling tasks with dynamic intervals.