Search code examples
javascriptrequestanimationframe

Why do many examples for requestAnimationFrame invoke requestAnimationFrame outside the callback?


Many examples I see online of RequestAnimationFrame call the function twice: inside and outside the callback. I understand why we call it inside; however, any reason why we call it outside?

Reference

let myReq;

function step(timestamp) {
  myReq = requestAnimationFrame(step); // I understand why we call it here.
  console.log(timestamp, myReq)
  if(timestamp >= 1000) {
    cancelAnimationFrame(myReq);
  }
}

myReq = requestAnimationFrame(step);  // why invoke rAF here.

Solution

  • That is the initial call to step, at the next animation frame; it is essentially kicking off the animation. Without it, you have this:

    let myReq;
    
    function step(timestamp) {
      myReq = requestAnimationFrame(step);
      console.log(timestamp, myReq)
      if(timestamp >= 1000) {
        cancelAnimationFrame(myReq);
      }
    }
    

    ...in which case, we never have a caller to step and it is never invoked.

    Alternately you could omit the requestAnimationFrame wrapper to the initial invocation of step:

    let myReq;
    
    function step(timestamp) {
      myReq = requestAnimationFrame(step); // I understand why we call it here.
      console.log(timestamp, myReq)
      if(timestamp >= 1000) {
        cancelAnimationFrame(myReq);
      }
    }
    
    myReq = step;  // why invoke rAF here.
    

    But then the very first time step is invoked it will not necessarily wait for the first available animation frame.