Cancellable IntervalLoading saved progress…

Cancellable Interval

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.

Signature

function cancellableInterval(fn, ms) {
  // starts an interval that calls `fn` every `ms` milliseconds
  // returns a function that, when called, stops the interval
}

Examples

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

Notes

  • Use setInterval and clearInterval — no setTimeout recursion.
  • Cancelling twice must not throw. The second call is a no-op.
  • Cancelling before the first tick must stop the interval — fn should never run.
  • Don't worry about pausing or resuming. Once cancelled, the interval is gone.
Loading editor…