The requestAnimationFrame() method tells the browser to perform the animation, and the browser optimally determines the timing of the redraw.

grammar

Receives a callback that takes a time parameter representing the time when requestAnimationFrame() starts executing the callback.

The return value is an ID, similar to the return value of setTimeout and setInterval, that can be passed to cancelAnimationFrame() to cancel the callback function.

Basic usage

Recursive calls

<div class="box"></div>
Copy the code
.box {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
}
Copy the code
const box = document.querySelector('.box')
let n = 10
let time = null

function anim(time) {
  box.style.left = n + 'px'
  n += 10
  if (time <= 500) {
    requestAnimationFrame(anim)
  } 
}

requestAnimationFrame(anim)
Copy the code

Refer to the link

  1. Using requestAnimationFrame
  2. requestAnimationFrame for Smart Animating
  3. window.requestAnimationFrame
  4. JavaScript Advanced Programming (4th Edition)
  5. The requestAnimationFrame is hailed as a magic artifact
  6. Optimize page performance using requestAnimationFrame instead of Throttle
  7. Understand requestAnimationFrame in depth
  8. CSS3 animation is so strong, requestAnimationFrame is still used?