84. fake timer (setInterval)を実装する

少し工夫が必要  - accepted / - tried

この問題は36. fake timer(setTimeout)を実装するの続きです。

setTimeoutと同じく、setInterval も精確ではない。(詳しくはEvent Loop で)。

ほとんどの場合はこれが問題にならないが、テストする時などではちょっと困る。

Event Loopの問題なく、精確なsetInterval()和clearInterval()を作ってくだい。これもFakeTimes がやっていることです。

「精確」というのは、関数の実行時間を0とし、時間は0からスタートすると、setInterval(func1, 100)ではfunc1が必ず以下の時間に実行される: 100、200、300 ...

Date.now()の実装も入れ替える必要がある。

class FakeTimer {
  install() {
    // replace window.setInterval, window.clearInterval, Date.now
    // with your implementation
  }
  
  uninstall() {
    // restore the original implementation of
    // window.setInterval, window.clearInterval, Date.now
  }
  
  tick() {
    // run the scheduled functions without waiting
  }
}

** 無限ループのご注意ください。** コードは大体こんな感じにジャッジされる。

const fakeTimer = new FakeTimer()
fakeTimer.install()

const logs = []
const log = () => {
    logs.push(Date.now())
}

let count = 0
const id = setInterval(() => {
  if (count > 1) {
    clearInterval(id)
  } else {
    log()
  }
  count += 1
}, 100)
// log 'A' at every 100, stop at 200
fakeTimer.tick()
fakeTimer.uninstall()
 
expect(logs).toEqual([100,200])

補足

時間に関係する関数の中ではDate.now()だけ対応が必要、その他は無視して良い。

考えを喋りながら。

(24)