Accessibility

Design Center Tutorial

Using ActionScript to pause and loop the timeline in Flash


Table of Contents

Pausing the main timeline

We have all seen those banner ads that play two or three times and are replaced by another version of the ad. To loop the main timeline three times—this is a popular number for banner ads—declare a loop variable in frame 1 and initialize it to 0. Here’s how they do it:

  1. Open the LoopTimeline.fla file. If you scrub the playhead across the timeline, the box, thanks to the tween, gets bigger.
  2. Add a keyframe to frame 15 of the scripts layer. Select the keyframe and open the Actions panel.
  3. Enter the following code into the Script pane:
    this.stop();

    This is the line that stops the playhead from moving forward, and it is also the line of code that can turn a millisecond into an eternity. If you stop the playhead, have a solid plan in place to get it back in motion.

  4. Press the Enter/Return key, and enter the following code:
    var timelinePause:Timer = new Timer(2000, 1);
    timelinePause.addEventListener(TimerEvent.TIMER, timerHandler);
    timelinePause.start();

    The first line tells Flash to create a Timer object. In ActionScript, when you use the class name followed by parentheses, you are creating what is called a constructor, which is a fancy term for an instance of a class. The numbers between the parentheses tell Flash the duration of the timer (2,000 milliseconds, or 2 seconds) and how often to wait around for that 2 seconds. The 1 means “only wait for it once."

    The next line tells Flash what to do when the two seconds are up; which is to execute a function named timerHandler. The final line tells Flash to reset the timer, and start the timer if it isn’t already running.

  5. Press the Enter/Return key and enter the following code:
    function timerHandler(evt:Object):void {
    this.play();
    }

    As you may have guessed, this is what happens when Flash waits around for the 2 seconds. The play() method simply tells the timeline to start playing again (see Figure 1).

  6. Save and test the movie. The box will grow, stop growing for 2 seconds, and then continue to grow.

     

    pausing the timeline

    (+) view larger
    Figure 1: Pausing the Flash timeline