Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Many animations do other things besides animation. For example, an animation may display narrative text as the animation proceeds, play music, or update a game scoreboard. Most of those types of activities do not need to be carried out 60 times per second so it’s important to be able to schedule tasks at alternate frame rates.
The code listed in Example 5.12 shows an animation loop for an application that updates a frames-per-second display once per second, by keeping track of the last time the display was updated.
Example 5.12. Scheduling tasks
var lastFpsUpdateTime = 0,
lastFpsUpdate = 0;
function animate(time) {
var fps = 0;
if (time == undefined) {
time = +new Date;
}
if (!paused) {
eraseBackground();
drawBackground();
update(time);
draw();
fps = calculateFps();
// Once per second, update the frame rate
if (now - lastFpsUpdateTime > 1000) {
lastFpsUpdateTime = now;
lastFpsUpdate = fps;
}
context.fillStyle = 'cornflowerblue';
context.fillText(lastFpsUpdate.toFixed() + ' fps', 50, 48);
}
}