mozRequestAnimationFrame and webkitRequestAnimationFrame

Published

Following on from my look at setInterval, I've been looking into these new global timing functions for use in animations. Firefox has mozRequestAnimationFrame and Chrome has webkitRequestAnimationFrame and if either of them are available in your browser it will be used to update the clock in the canvas below.

There is a clock here - if you can't see it, your browser does not support the canvas element.

These functions act similarly to setTimer, though they trigger the callback function when the browser thinks it is time to update the page instead of at a fixed interval.

If you change to another browser tab or minimize the window then the script will go to sleep - on Firefox it will continue to receive updates about once a second, but on Chrome the updates will stop. Updates resume at full speed when the page becomes active again.

Here is how the script uses these functions to update the clock:

function draw() {
  // draw the clock
}
function frame(e) {
  draw();
  nextFrame(frame);
}
function start(cid) {
  ...
  nextFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
  if(nextFrame)
    nextFrame(frame);
  else
    setInterval(draw, interval);
  ...
}
The function to use, either window.mozRequestAnimationFrame or window.webkitRequestAnimationFrame, is stored in the nextFrame variable so I don't have to check which to use every time. If neither of the functions are available, the script falls back to using setInterval to periodically call the draw function directly. Otherwise, the frame function is used to wrap the call to draw with the subsequent nextFrame call.

webkitRequestAnimationFrame also has an optional second argument (which I'm not using) to specify the element to be updated. This is so that the timer can be stopped for elements that are not visible on the page.

The text on the canvas above shows the timer method being used, the mean average time for all intervals since the clock was started and the maximum and minimum intervals. All these measurements are taken using the Javascript date functions, and I have made no attempt to determine how accurate they are.

The more interesting statistic comes from looking at the CPU usage in Process Explorer. With the clock open on a tab Firefox uses 25-30% CPU. Switching to another tab with a static page, the CPU usage drops down below 1%, and the usage numbers are fairly similar for Chrome. Trying the same page in Opera shows that the CPU usage remains constant while the clock page is inactive (though since I used a relatively long interval of 50ms for the setInterval fallback, CPU usage remains much lower at around 3-4%).

« Previous: TagCanvas 1.7 Next: SVGGraph 2.3 »

This site uses cookies - details here.