What's the best way to use requestAnimationFrame and fixed frame rates

Posted by m90 on Programmers See other posts from Programmers or by m90
Published on 2012-11-15T10:02:59Z Indexed on 2012/11/15 11:21 UTC
Read the original article Hit count: 198

Filed under:
|
|

I recently got into using the HTML5-requestAnimationFrame-API a lot on animation-heavy websites, especially after seeing the Jank Busters talk. This seems to work pretty well and really improve performance in many cases.

Yet one question still persists for me: When wanting to use an animation that is NOT entirely calculated (think spritesheets for example) you will have to aim for a fixed frame rate. Of course one could go back to use setInterval again, but maybe there are other ways to tackle this.

The two ways I could think of using requestAnimationFrame with a fixed frame rate are:

var fps = 25; //frames per second

function animate(){

   //actual drawing goes here
   setTimeout(function(){
      requestAnimationFrame(animate);
   }, 1000 / fps)

}

animate();

or

var fps = 25; //frames per second

var lastExecution = new Date().getTime();

function animate(){

    var now = new Date().getTime();

    if ((now - lastExecution) > (1000 / fps)){
        //do actual drawing
        lastExecution = new Date().getTime();
    }

    requestAnimationFrame(animate);

}

animate();

Personally, I'd opt for the second option (the first one feels like cheating), yet it seems to be more buggy in certain situations.

Is this approach really worth it (especially at low frame rates like 12.5)? Are there things to be improved? Is there another way to tackle this?

© Programmers or respective owner

Related posts about JavaScript

Related posts about html5