19 December 2012

How to loop a Flash banner three times

Some websites require that Flash banners only loop three times; I was recently creating such a banner and needed a solution. Luckily, I stumbled across this elegant solution on David Stiller's blog: http://www.quip.net/blog/2006/flash/how-to-loop-three-times

This particular solution is for Actionscript v2, however, there is one available for v3 too, see the website for more info.

For now, here's the AS2 version:

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.


No comments:

Post a Comment