Home
← All questions

setCancellableInterval in JavaScript

MediumPremiumJavaScript

Asked at Coinbase

JavaScript interview practice: Implement setInterval that returns a cancel function instead of a timer ID.

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
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium