Sohail
Sohail

Reputation: 2332

interval between function calls with requestAnimationFrame varies

I am trying to animate a Sequence of JPG images using requestAnimationFrame , however I noticed that sometime it takes a bit longer on some frames.

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.oRequestAnimationFrame      ||
    window.msRequestAnimationFrame     ||
    function( callback ){
        window.setTimeout(callback, 1000 / 60);
    };
})();

var start;
var i=0;
var animateLoop = function() {

    if(i>500) {
        return false;
    }
    i++;
    requestAnimFrame(animateLoop);
    var _start = start;
    start = +new Date();
    console.log("Iteration:"+i, "Milliseconds Diff: "+(start-_start));
   }

animateLoop();

To elaborate, please have a look at this fiddle : https://jsfiddle.net/bhenqfbw/

If you run this while the console is open, you will see that the milliseconds difference between each call is not the same. and in my case where I change the image source in this function, the fluctuation is even higher.

is there a way I can make it constant or it just has to be this way ?

Upvotes: 2

Views: 1107

Answers (2)

Ali Gorkem Cicek
Ali Gorkem Cicek

Reputation: 21

requestAnimationFrame is not time based. You should make your animation time based, not frame.

Basically if you want to change an element's position with a constant value and you don't have a fixed frame rate, you can use the time difference between frames to calculate the distance in each frame.

Here's the main idea: (check out console) https://jsfiddle.net/bhenqfbw/1/

Upvotes: 2

Edwin Reynoso
Edwin Reynoso

Reputation: 1531

Well the point of requestAnimationFrame is for the browser to decide when to call that function again. It's optimized for that. Therefore that's the best option. Yet if you really want something aggressive that doesn't care whether the function finished being called setInterval is your friend (I mean enemy because it's pretty bad). Or:

function toCall(){
  //do stuff
  setTimeout(toCall); //Place this at the end of your function. And no second parameter needed. It'll be called whenever the stack is empty.
}

Upvotes: 1

Related Questions