HTML and CSS Reference
In-Depth Information
Calling requestAnimationFrame
One of the best features of requestAnimationFrame is that it will be scheduled to run before the web browser performs
a repaint, which in most browsers happens approximately 60 times per second (that is, 60 FPS). This basically means
that requestAnimationFrame cannot be called more times than the number of repaints in the browser. When the
browser window (or tab) goes inactive, the number of times that the function is called per second will be reduced
automatically to a minimum.
Browsers as recent as IE9 didn't support requestAnimationFrame , but luckily there's a very easy way to polyfill it
(which means creating a way to make it work similarly in older browsers) by using a RequestAnimationFrame Polyfill,
as shown in Listing 8-3.
Listing 8-3. Using a RequestAnimationFrame Polyfill
// handle multiple browsers for requestAnimationFrame()
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
// if all else fails, use setTimeout
function (callback) {
// shoot for 60 fps
return window.setTimeout(callback, 1000 / 60);
Therefore, you can implement an update loop as shown in Listing 8-4.
Listing 8-4. Implementing an Update Loop
// Define the amount of times the loop is going to get called
var maxCount = 3;
// Call update() for the first time
function update(current) {
// Execute the function 3 times
if (current < maxCount) {
// Do Something
// Call requestAnimFrame
requestAnimFrame(function() {
// Increase the value of current by one
update(current + 1);
Search WWH ::

Custom Search