Reputation: 21985
I'm wondering if I should switch my game over to requestAnimationFrame. If there even is still a reason to do so anymore, as I've read that setTimeout() now also pauses when you switch tabs in the major browsers.
Anyway, say I want to control the FPS of my animation.
Currently I can do it like this:
k.state.loopinterval =
window.setInterval(renderLoop(), 1000 / k.settings.engine.fps );
Where k.settings.engine.fps
is the wanted fps.
If I do it the requestAnimationFrame
way, I lose that possibility, and it'll just give me whatever it can give:
window.requestAnimFrame(k.operations.startLoop);
renderLoop();
I have seen some people suggest to place the requestAnimFrame in another loop:
setInterval( function () {
requestAnimationFrame( draw );
}, 1000 / 60 );
So... What should I go with? Leave it as it is?
What are the exact benefits of requestAnimationFrame, now that setTimeout is also paused when switching tabs?
Upvotes: 7
Views: 2373
Reputation: 2879
requestAnimationFrame is the correct way to make animations.
Why?
Because the browser can optimize the render for make a smoother animation. Answering the question, another way is:
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element){
window.setTimeout(callback, 1000 / 60);
};
})();
And there is a other way in link below.
When you call requestAnimation, you make the browser understand when is the moment to redraw the html. If you make animation/transitions in CSS and move stuff or change background (as sprites), using requestAnimation will make the render works when you call requestAnimation. Without it, the browser will render anything in which time, what can make more redraws then needed.
Even, the way the browsers are going on, it will do more optimizations than we don't know yet. Make the browser understand what we are doing and then they help us.
I found this link, can add some more ideas
Upvotes: 5