joken-前端工程师

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

概述

  • requestAnimationFrame 是根据帧数来执行回调函数的,就是屏幕一帧,那 requestAnimationFrame就会执行一次。一般屏幕是60帧,也就是一秒执行60次回调函数.
  • 性能相对定时器settimeout好,因为定时器执行权限在同步任务 微任务之后,会受到其他任务影响。

requestAnimationFrame

image

逻辑上和宏任务 微任务无关系

image

使用方式示例

类似递归调用

const element = document.getElementById("some-element-you-want-to-animate");
let start, previousTimeStamp;
let done = false;

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

  if (previousTimeStamp !== timestamp) {
    // 这里使用 Math.min() 确保元素在恰好位于 200px 时停止运动
    const count = Math.min(0.1 * elapsed, 200);
    element.style.transform = `translateX(${count}px)`;
    if (count === 200) done = true;
  }

  if (elapsed < 2000) {
    // 2 秒之后停止动画
    previousTimeStamp = timestamp;
    if (!done) {
      window.requestAnimationFrame(step);
    }
  }
}

window.requestAnimationFrame(step);

posted on 2024-06-03 21:27  joken1310  阅读(6)  评论(0编辑  收藏  举报