Problem
Implement a function setCancellableInterval that acts like setInterval, but instead of returning a timer ID, returns a function that cancels the interval when called.
It should support the same signature as setInterval:
setCancellableInterval(callback);
setCancellableInterval(callback, delay);
setCancellableInterval(callback, delay, param1);
setCancellableInterval(callback, delay, param1, param2);
setCancellableInterval(callback, delay, param1, param2, /* … ,*/ paramN);
Example
let i = 0;
// t = 0:
const cancel = setCancellableInterval(() => {
i++;
}, 10);
// t = 10: i is 1
// t = 20: i is 2
cancel(); // called at t = 25
// t = 30: i is still 2 — the interval callback has stopped running