requestAnimationFrame替代setTimeout、setInterval

requestAnimationFrame相較於setTimeout、setInterval的優勢這裏很少說,想要了解的同窗能夠戳requestAnimationFrame最佳實踐
requestAnimationFrame原生沒有自定義時間間隔執行的功能,好比想要實現每隔1s執行一次的功能或者延時1s執行,每次都要重寫間隔時間的重複代碼,想着能夠將之抽出。直接上代碼:前端

const RAF = {
  intervalTimer: null,
  timeoutTimer: null,
  setTimeout (cb, interval) { // 實現setTimeout功能
    let now = Date.now
    let stime = now()
    let etime = stime
    let loop = () => {
      this.timeoutTimer = requestAnimationFrame(loop)
      etime = now()
      if (etime - stime >= interval) {
        cb()
        cancelAnimationFrame(this.timeoutTimer)
      }
    }
    this.timeoutTimer = requestAnimationFrame(loop)
    return this.timeoutTimer
  },
  clearTimeout () {
    cancelAnimationFrame(this.timeoutTimer)
  },
  setInterval (cb, interval) { // 實現setInterval功能
    let now = Date.now
    let stime = now()
    let etime = stime
    let loop = () => {
      this.intervalTimer = requestAnimationFrame(loop)
      etime = now()
      if (etime - stime >= interval) {
        stime = now()
        etime = stime
        cb()
      }
    }
    this.intervalTimer = requestAnimationFrame(loop)
    return this.intervalTimer
  },
  clearInterval () {
    cancelAnimationFrame(this.intervalTimer)
  }
}
複製代碼

進行簡單測試:bash

let count = 0
function a() {
  console.log(count)
  count++
}
RAF.setInterval(a, 1000)
複製代碼

這裏沒有實現setTimeout、setInterval的返回值功能,不過返回值功能大多用在清除定時器上,目前提供了clearTimeout和clearInterval的方法,因此返回值能夠沒必要返回。
知乎專欄:葉雨森·前端雜談oop

相關文章
相關標籤/搜索