How to Loop a Movie Three Times (AS2)

ActionScript 2.0 Flash

Note:  An ActionScript 3.0 version of this article is located in a more recent entry of this blog.

Truth be told, this article should actually be titled “How to Loop a Movie As Many Times as You Like.”  It just happens that when people ask about this topic, the most popular number seems to be three. 

An answer, short and sweet

Add a keyframe to the last frame of your movie.  Any layer will do, but if you like to be organized, create a dedicated scripts layer.  Click into this concluding keyframe and paste the following ActionScript.

if (!loopCount) {
  var loopCount:Number = 0;
}
loopCount++;
if (loopCount >= 3) {
  this.stop();
}

How it works

An if statement checks to see if a variable named loopCount exists.  If it doesn’t, this variable is created and initialized to a value of zero.  During the movie’s first run, loopCount won’t exist, of course, and will be created.  During subsequent runs, the variable creation will be ignored.

The ++ operator increments loopCount by one.

Another if statement checks to see if loopCount’s value is equal to or greater than three.  If it is, the MovieClip.stop() method is invoked on the main timeline, which halts the movie.  On the movie’s first and second run, loopCount will be less than three, so the movie will automatically loop.

Variations

If you want the movie to five times, change that three to a five.  For fifteen loops, change it to a 15.  You get the idea. :)   If you only want the movie to play once, scrap all of the above and simply put this.stop(); instead.

If you want the movie to loop, but not from the beginning — that is, start on frame 1, play through frame 300, then loop from 100 through 300 — alter the code like this:

if (!loopCount) {
  var loopCount:Number = 0;
}
loopCount++;
if (loopCount >= 3) {
  this.gotoAndPlay(100);
}

… replacing 100 with whatever frame number you please.

Leave a Reply