83. 实现一个interval

JavaScript TikTok Meta

中等难度  -通过 / -执行

请实现一个mySetInterval(a, b),这个和window.setInterval()不太一样,时间间隔不是固定的,而是一个线性函数越来越大 period = a + b * count

let prev = Date.now()const func = () => {  const now = Date.now()  console.log('roughly ', Date.now() - prev)  prev = now}const id = mySetInterval(func, 100, 200)// 100左右,100 + 200 * 0// 400左右,100 + 200 * 1// 900左右,100 + 200 * 2// 1600左右,100 + 200 * 3
....
myClearInterval(id) // 停止interval
  1. mySetInterval(delay, period)delay用于第一次间隔,然后period会被叠加

  2. 因为 window.setTimeout 和 window.clearTimeout 并不精确。所以在test你写的代码的时候,这两个方法会被替换为静态的实现。不过不用担心,interface是一样的。

大概会按照以下的样子进行代码测试。(仅作参考,你不需要理解以下代码)

let currentTime = 0const run = (delay, period, clearAt) => {  currentTime = 0  pipeline.length = 0    const logs = []  const func = () => {    logs.push(currentTime)  }  mySetInterval(func, delay, period)  if (clearAt !== undefined) {    setTimeout(() => {      myClearInterval(id)    }, clearAt)  }  while (pipeline.length > 0 && calls.length < 5) {    const [time, callback] = pipeline.shift()    currentTime = time    callback()  }  return calls}expect(run(100, 200)).toEqual([100,400,900,1600,2500])expect(run(100, 200, 450)).toEqual([100,400])expect(run(100, 200, 50)).toEqual([])

始终思考更好的解决办法