Skip to content
Onsite

setInterval Using setTimeout

MediumP2Coding

Implement mySetInterval(fn, delay, ...args) and myClearInterval(id) using only setTimeout and clearTimeout (do not call setInterval).

  • mySetInterval calls fn(...args) repeatedly, every delay milliseconds, and returns an id that identifies the interval. The first call happens after delay ms, not immediately. The next wait starts after fn returns.
  • myClearInterval(id) stops that interval. It must work when called from inside fn (no further call may happen), and calling it with an unknown or already cleared id does nothing.
  • Different intervals have different ids and do not affect each other.

Example 1

Input
const id = mySetInterval(() => log('tick'), 100); // later myClearInterval(id);
Output
'tick' is logged every 100 ms until cleared

Constraints

  • 1 <= delay <= 10^4

Hints

Run checks the 3 visible tests, Submit all 8.