阅读 488

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)
  }
}
复制代码

进行简单测试:

let count = 0
function a() {
  console.log(count)
  count++
}
RAF.setInterval(a, 1000)
复制代码

这里没有实现setTimeout、setInterval的返回值功能,不过返回值功能大多用在清除定时器上,目前提供了clearTimeout和clearInterval的方法,所以返回值可以不必返回。
知乎专栏:叶雨森·前端杂谈

关注下面的标签,发现更多相似文章
评论