Skip to content

2805. Custom Interval

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let id = 0;
const idToTimeout = {};

function customInterval(fn: Function, delay: number, period: number): number {
  ++id;
  (function callFnWithCountPlusOne(count: number): void {
    const timeout = setTimeout(() => {
      fn();
      callFnWithCountPlusOne(count + 1);
    }, delay + period * count);
    idToTimeout[id] = timeout;
  })(0);
  return id;
}

function customClearInterval(id: number): void {
  clearTimeout(idToTimeout[id]);
}