Using This Magical Function
The way you use requestAnimationFrame
is very simple. Whenever you want to redraw your screen, simply call it along with the name of your animation loop function (aka a callback) that is responsible for drawing stuff to your screen:
requestAnimationFrame(callback);
The thing to note is that the requestAnimationFrame
function isn’t a loop. It isn’t a timer. You need to call it every time you want to get the screen repainted. This means, unless you want your animation to stop, you need to call requestionAnimationFrame
again through the same callback function that you specified. I know that sounds bizarre, but it looks as follows:
function animate() {// stuff for animating goes hererequestAnimationFrame(animate);}animate();
The animate
method is the callback function for our requestAnimationFrame
call, and it will get called very rapidly once it starts running.
Vendor Prefixes Not Needed
At this point,
requestAnimationFrame
has extremely broad support among the browsers people use according to the caniuse statistics for it. There is no need to vendor prefix it anymore, so I would suggest saving some lines of code from having to do that.