Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you put requestAnimationFrame before the function body?

For as long as I have been writing for the canvas, I've always done the following:

function animate() {
  //do stuff in the animation

  requestAnimationFrame(animate);
}

Lately though, I have frequently seen it done this way:

function animate() {
  requestAnimationFrame();

  //do stuff in the animation
}

While I can of course see benefits for doing it my way, (mainly, if there's a bug it won't continue to call more frames) I have been unable to find any benefits for calling for the next frame first.

Does anyone have an explanation for this/possible benefits for doing it this way? Or, can you prove it shouldn't be done this way? A source is definitely needed, as I've seen it all over the web but no one can really give a concrete reason for it.

like image 873
Danie Clawson Avatar asked Aug 15 '15 00:08

Danie Clawson


1 Answers

The placement of the rAF call is clearer if you keep in mind that requestAnimationFrame is just requesting a ride on the next animation processing cycle -- it's not actually triggering the animation processing cycle.

Calling for the next rAF frame immediately will give you the best chance of catching the very next rAF cycle execution.

For example, if your "stuff" takes about 3ms to execute and the next rAF cycle starts in 4ms then you might catch the next cycle in 4ms rather than the subsequent cycle in 4+16ms. It might seem impossible that you would miss the next rAF cycle since you have 4-3==1ms to spare (nearly an eternity for the cpu), but the system might schedule other things that eat up your 1ms margin (like garbage collection).

On the other hand, if your "stuff" averages 15ms to complete then put your rAF call at the end. Putting it last might miss an execution once & a while, but it is probably better than risking multiple "stuff"s piling up.

With this in mind, very generally, putting the rAF call at the end is safer at the occasional cost of a missed rAF cycle.

like image 55
markE Avatar answered Oct 24 '22 23:10

markE