requestAnimation Frame Testing

by ShaCP

HTML

<div id="d">
</div>

CSS

#d {
  width: 100px;
  height: 100px;
  background-color: lightskyblue;
  /* animation: move 2s linear forwards; */
}

/* @keyframes move {
  to {
  transform: translateY(200px);
  }
} */

JavaScript

console.clear();

/* let i2 = 0; */
/* setInterval(() => console.log(i2++), 1000) */


/* let i = 1; */

const element = document.getElementById("d");
const duration = 2;
const durationInMs = duration * 1000;
const pixelsToMove = 200;
const speed = pixelsToMove / durationInMs;
let rafId;
let lastTimeStamp;
let endOfRafCallback;
let start;


function step(timestamp) {
  let callbackStart;
  let elapsed;
  console.log("-------- start of rAF, ID", rafId, "callback ----------" /* i++,  */,`

time at start of rAF callback`, callbackStart = performance.now(),`

time since end of last rAF callback`, callbackStart - endOfRafCallback,`

time of default timestamp passed to rAF callback`, timestamp, `

time elapsed between ${rafId === 1 ? "first call to rAF and first rAF callback's built-in timestamp" :
"current and last built-in rAF callback timestamps"}`, timestamp - lastTimeStamp, `

time elapsed from first call to rAF to current rAF callback's built-in timestamp`, elapsed = timestamp - start, `

pixels translated so far`, speed * elapsed);
  lastTimeStamp = timestamp;
  /*   if (start === undefined)
      start = timestamp; */
  /* const elapsed = timestamp - start; */
/*   console.log("time elapsed from first call to rAF to current rAF callback's built-in timestamp", elapsed, `
  pixels translated so far`, speed * elapsed); */
  // `Math.min()` is used here to make sure that the element stops at exactly 200px.
  element.style.transform = 'translateX(' + Math.min(speed * elapsed, pixelsToMove) + 'px)';

  if (elapsed < durationInMs) { // Stop the animation after 2 seconds
    /* uncomment the below to see that if your callback's work takes too long, your
    animation won't be as smooth because it won't be updated every ~16ms (repaint
    interval for 60hz), so really the interval won't be ~16ms but whatever the time
    elapsed is between callbacks. What I'm doing here is adding 50ms of lag by. Check
    the times elased in the console, they're 50ms away.*/
  var b =...