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:
var loop:Number = 0;
Nothing new here—you create a variable named loop and give it a number value of 0. In many respects, what you are doing here is setting the initial value, because all of the action in this example takes place between frames 2 and 30.
loop = loop + 1;
if (loop < 3) {
this.gotoAndPlay(2);
} else {
this.stop();
}
Let’s take a look at what you have done. The first line adds 1 to the value of the variable you named loop in the first frame. The next four lines are the conditional statement that essentially says, "If the value of loop is 1 or 2 (if loop < 3), then scoot the playhead back to frame 2 (this.gotoAndPlay(2)). If it is already 3—else—then stay put on frame 30."
The first time the playhead hits frame 30, the value of loop is 1, and the playhead scoots back to frame 2. (The reason it goes to frame 2 is because frame 1 would set the value of loop to 0 again.) The next time it hits frame 30, the value of loop is changed to 2 and, again, the playhead scoots back to frame 2 and plays the animation. This time, when the playhead hits frame 30, the value of loop is changed to 3, and the playhead stays put on frame 30.