CodePark/ problems / Cancellable interval
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Timers and scheduling

Cancellable interval

easyabout 10 minutes in an interview

Implement setCancellableInterval(callback, delay, ...args). It calls callback(...args) every delay milliseconds. It returns a cancel function.

  • The first call happens after delay ms, not right away.
  • Calling cancel stops all future calls. Calling it again does nothing.
  • After cancel, no timer is left waiting to run.
  • Each call to setCancellableInterval is independent. Cancelling one doesn't affect another.
Input: const cancel = setCancellableInterval(tick, 100); // 350 ms pass cancel(); Output: tick was called 3 times (at 100, 200 and 300 ms)
Input: setCancellableInterval(log, 50, 'a', 1); Output: log('a', 1) every 50 ms