requestAnimationFrame API , 顾名思义,请求动画帧,也称 帧循环
浏览器刷新每一帧的时候都会执行 API 内的回调函数

返回值

一个 long 整数,请求 ID ,是回调列表中唯一的标识。是个非零值,没别的意义。

  1. (() => {
  2. const beginBtn = document.querySelector("#begin")
  3. const endBtn = document.querySelector("#end")
  4. let myRef;
  5. beginBtn.addEventListener("click", () => {
  6. myRef = requestAnimationFrame(test)
  7. })
  8. endBtn.addEventListener("click", () => {
  9. cancelAnimationFrame(myRef) // 取消帧循环
  10. })
  11. function test() {
  12. myRef = requestAnimationFrame(test)
  13. console.log('🚀🚀~ myRef:', myRef);
  14. }
  15. })()

使用