Skip to content Skip to sidebar Skip to footer

Requestanimationframe And Setinterval Animating At A Different Pace

I am translating two divs using setInterval and requestAnimationFrame. Animated using interval, the div translates at a rate of 3px per (1000/60)ms, which equates to 180px per 1000

Solution 1:

There is a absolutely no guarantee that your iterval will run at the requested rate so just adding some constant every callback like the code does for the setInterval case isn't going to match.

you could use performance.now or Date.now as your clock in the setInterval case

let interval = document.querySelector('.interval')
let raq = document.querySelector('.raq')

functionstartAnimation() {
  setInterval(() => {
    const translateValue = (performance.now() * 0.18) % 300
    interval.style.transform = `translateX(${translateValue}px)`
  }, 1000 / 60)

  letraqAnimation = (timeElapsed) => {
    let translateValue = (timeElapsed * 0.18) % 300
    raq.style.transform = `translateX(${translateValue}px)`window.requestAnimationFrame(raqAnimation)
  }

  window.requestAnimationFrame(raqAnimation)
}

window.setTimeout(startAnimation, 1000)
.interval,
.raq {
  width: 50px;
  height: 50px;
  border-radius: 5px;
  background-color: #121212;
  margin: 1rem;
}
<divclass="interval"></div><divclass="raq"></div>

they still may not perfectly align though as (a) they are actually running at different times and so get different time values and (b) the run at different rates. They will be close though since it's effectively the same clock

Post a Comment for "Requestanimationframe And Setinterval Animating At A Different Pace"