requestAnimationFrame 一种更好的循环方式

requestAnimationFrame 一种更好的循环方式

window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行

在大多数遵循W3C建议的浏览器中,回调函数执行次数通常与浏览器屏幕刷新次数相匹配。为了提高性能和电池寿命,因此在大多数浏览器里,当requestAnimationFrame() 运行在后台标签页或者隐藏的 iframe 里时,requestAnimationFrame() 会被暂停调用以提升性能和电池寿命。

const element = document.getElementById('some-element-you-want-to-animate');
let start;

function step(timestamp) {
  if (start === undefined)
    start = timestamp;
  const elapsed = timestamp - start;

  //这里使用`Math.min()`确保元素刚好停在200px的位置。
  element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';

  if (elapsed < 2000) { // 在两秒后停止动画
    window.requestAnimationFrame(step);
  }
}

window.requestAnimationFrame(step);

参数

callback
下一次重绘之前更新动画帧所调用的函数(即上面所说的回调函数)。该回调函数会被传入DOMHighResTimeStamp参数,该参数与performance.now()的返回值相同,它表示requestAnimationFrame() 开始去执行回调函数的时刻。

返回值

一个 long 整数,请求 ID ,是回调列表中唯一的标识。是个非零值,没别的意义。你可以传这个值给 window.cancelAnimationFrame() 以取消回调函数。

setTimeout 循环对比

setTimeout 和 requestAnimationFrame 的写法类似,相交于setInterval来说,可以控制开始的时间,防止循环内容太多,引起卡顿

changeImg(index) {
    if (this.fileNames.length > 0) {
      this.fileNamesIndex++
      if (this.fileNamesIndex >= this.fileNames.length) {
        this.fileNamesIndex = 0
      }
      this.timer = setTimeout(this.changeImg.bind(this, index), 2000)
    }
  }

  heatBtnClick(index) {
     if (this.timer) {
       clearTimeout(this.timer)
       this.timer = null;
     }
    if (this.fileNames.length > 0) {
      this.timer = setTimeout(this.changeImg.bind(this, index), 2000);
    }
  }
posted @ 2021-12-29 13:16  纯蓝晴空  阅读(304)  评论(0)    收藏  举报