7.8. Performing Repeated Actions on Movie Clips

Problem

You want to perform a particular action on a movie clip repeatedly.

Solution

Use an onEnterFrame( ) event handler method or use setInterval( ).

Discussion

Every movie clip’s onEnterFrame( ) method is called repeatedly during a Flash movie’s playback. If a movie clip’s onEnterFrame( ) method is defined, any actions it contains are automatically invoked at the frequency of the movie’s frame rate. For example, if a movie’s frame rate is set to 12 frames per second, actions defined within a movie clip’s onEnterFrame( ) method are invoked 12 times per second. Here is an example using onEnterFrame( ), which shows that it is called at approximately the frame rate. You will notice that it is not exact. The precision to which the movie plays back at the correct frame rate depends on the computer’s processor and what else is being processed at the same time as the Flash movie.

// Define an onEnterFrame(  ) method for an existing movie clip named myMovieClip.
myMovieClip.onEnterFrame = function (  ) {

  // Store the number of milliseconds since the movie started to play.
  var currentTime = getTimer(  );
 
  // Calculate the difference between the current time and the time of the previous
  // call to onEnterFrame(  ), which gives you the elapsed time between calls. The
  // first time through, prevTime is undefined.
  var timeElapse = currentTime - this.prevTime;

  // Display the timeElapse times 12 (or the movie's frame rate if it is not 12). // This will ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.