
Sponsored
Sponsored
This approach leverages JavaScript's setInterval function to repeatedly invoke a function at specified intervals. The function is initially called immediately, then periodically every t milliseconds. A separate cancellation function is prepared using clearInterval to stop the repeated invocation when it's called after cancelTimeMs.
Time Complexity: O(1) per function call, ignoring the delay.
Space Complexity: O(1) as no additional data structures are used.
1function cancellable(fn, args, t) {
2 fn(
This implementation of the cancel function sets up an interval using setInterval. Initially, the function fn is called with the provided args. Then, every t milliseconds, the setInterval calls the function again. The clearInterval function is returned to stop further executions when called.
This approach uses recursive calls to setTimeout to simulate the behavior of setInterval. This gives finer control over each invocation of the function, and you can easily stop future calls by not setting further timeouts.
Time Complexity: O(1) per function call, ignoring the delay.
Space Complexity: O(1) as only a boolean flag is used to manage state.
1function cancellable(fn, args, t) {
2 let isActive = true;
3 const callFn = () => {
4 if (!isActive) return;
5 fn(...args);
6 setTimeout(callFn, t);
7 };
8 callFn();
9 return function cancelFn() {
10 isActive = false;
11 };
12}
13
14// Example usage:
15const cancelTimeMs = 200;
16const cancelFn = cancellable((x) => console.log(x * 2), [4], 35);
17setTimeout(cancelFn, cancelTimeMs);This code sets up a manual loop using setTimeout. The helper function callFn checks if the process is still active, invokes the function, and schedules the next invocation with setTimeout. The returned cancelFn sets the flag isActive to false, stopping further invocations.