Cancellable Interval
Prompt
Create a function called setCancellableInterval
that works like JavaScript's built-in setInterval
, but with an easy way to stop it.
Your function should accept a callback function and a time interval in milliseconds. It should run the callback repeatedly at the specified interval. Most importantly, it should return a function that, when called, will stop the repeating execution.
This is helpful when you need to perform a task repeatedly, but also want a simple way to stop it when needed.
Example
const cancelTask = setCancellableInterval(
() => console.log('Executing periodic work'),
1000
);
// Stop execution when needed
setTimeout(cancelTask, 5000);
Playground
Solution
Explanation
The solution to this problem involves creating a wrapper around JavaScript's built-in interval functionality that returns a cancellation function.
Let's break down the implementation step by step:
First, we create our setCancellableInterval
function that takes three parameters:
func
: The callback function to execute at each intervaldelay
: The time in milliseconds between executions...args
: Any additional arguments that should be passed to the callback function
function setCancellableInterval(func, delay, ...args) {
// Implementation here
}
Inside this function, we use the native setInterval
method to create our recurring task:
const timerId = setInterval(func, delay, ...args);
This gives us a unique identifier (the timer ID) that we can use later to cancel the interval.
The key part of our solution is that we return a function that, when called, will clear the interval:
return () => {
clearInterval(timerId);
};
This creates a closure that "remembers" the timer ID even after our main function has finished executing. When this returned function is called, it uses clearInterval()
with the stored ID to stop the recurring executions.
The beauty of this pattern is in its simplicity and usability. Consider how we use it:
const cancelTask = setCancellableInterval(() => console.log('Task executing'), 1000);
// Later, when we want to stop the interval:
cancelTask();
This provides a clean interface for setting up recurring tasks that can be easily cancelled when needed. The implementation uses the closure pattern to maintain access to the timer ID, which is a common and powerful JavaScript technique.
We can also simplify the implementation by passing the callback function and delay as arguments to the setInterval
method:
function setCancellableInterval(...args) {
const timerId = setInterval(...args);
return () => {
clearInterval(timerId);
};
}
We can also simplify the implementation by passing the callback function and delay as arguments to the setInterval
method:
function setCancellableInterval(...args) {
const timerId = setInterval(...args);
}