Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 5. Animation > 5.3. Scheduling Tasks at Alternate Frame Rates

5.3. Scheduling Tasks at Alternate Frame Rates

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);
   }
}


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint