You schedule a recurring task with setInterval, then realise you have nowhere clean to keep the returned id so you can stop it later. The usual mess is a global let intervalId floating somewhere far from where the interval was started.
Implement a cancellableInterval function that takes a callback fn and a delay ms, starts a repeating interval, and returns a cancel function. Calling cancel() stops the interval. Calling it again does nothing.
function cancellableInterval(fn, ms) {
// starts an interval that calls `fn` every `ms` milliseconds
// returns a function that, when called, stops the interval
}
let count = 0;
const cancel = cancellableInterval(() => count++, 100);
// After 350ms: count === 3
cancel();
// No further ticks
const cancel = cancellableInterval(() => console.log('tick'), 50);
cancel();
cancel(); // safe — second call is a no-op
// 'tick' is never logged
setInterval and clearInterval — no setTimeout recursion.fn should never run.