O'Reilly logo

Supercharged JavaScript Graphics by Raffaele Cecco

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Timers, Speed, and Frame Rate

This section deals with programming issues related to throttling graphical updates in JavaScript to give the user an optimal experience. We want graphics that have smooth and fluid movement, and that are neither too quick nor too slow. The performance of the user’s computer will influence how fast moving graphics are updated. I’ll also discuss a solution for reducing these apparent speed variations on different machines.

Using setInterval and setTimeout

JavaScript’s setInterval() and setTimeout() functions allow you to call JavaScript code at regular intervals. Applications that require regular graphical updates, such as arcade games, would be difficult, if not impossible, to write without them.

You can call a function repeatedly by passing it as a callback to setInterval():

// This is a callback function.
var bigFunction = function() {
    // Do something...
    // This code needs to be called regularly.
    // It takes 20ms to execute
};

// setInterval will attempt to call bigFunction() every 50 milliseconds.
setInterval(bigFunction, 50);

Notice that bigFunction() takes 20 milliseconds (ms) to execute. What happens if a smaller interval is used instead?

setInterval(bigFunction, 15);

It might seem that the 20ms bigFunction() will be called again before the first callback has even returned. In reality, the new callback will be queued until after the first callback has finished.

What happens if the delay is reduced further?

setInterval(bigFunction, 5);

It would be reasonable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required