Timer Delay in Actionscript 3.0
If you’re like me, you’ve found youself with a flash file that goes on for hundreds of frames because you have animations that need to happen after 5 or 10 seconds and you’re adding frames to get that delay. Well, AS3 makes it pretty simple to use a script based delay timer and keep your movie more compact.
Here’s some basic, uncommented code that stops the movie, waits 2500ms, then plays the movie again:
stop();
import flash.utils.*;
var myTimer:Timer = new Timer(2500);
myTimer.addEventListener(”timer”, timedFunction);
myTimer.start();
function timedFunction(eventArgs:TimerEvent) {
myTimer.stop();
play();
//trace(”Timer fired ” + myTimer.currentCount + ” times.”);
}
Learn more about the Timer class (with some documented code) here. If you have any questions, feel free to ask in the comments.
Additional note:
If you want to use a stop(); command to stop playback later in the movie, you may need to add:
myTimer.removeEventListener(”timer”, timedFunction);
after your stop(); command. Um, I’m sure that’s because this is not the ideal way to pause a movie for a delay, but whatever… this still works. If someone has a better code sample to submit- please feel free!
July 28th, 2009 at 11:46 am
Hi,
Well, I’ve been checking the code that show above, and there is a mistake when you declare an EventListener. So you do:
myTimer.addEventListener(”timer”, timedFunction);
but the correct form is as following:
myTimer.addEventListener(TimerEvent.TIMER, timedFunction);
Well, now all code is correct. that is all!
bye.
August 10th, 2009 at 7:03 pm
I was looking for a simple time delay in ActionScript, and I found this one to be useful (and working). The logic is plain simple to understand.
December 8th, 2009 at 3:23 pm
For what it’s worth, “timer” is acceptable in the above code. However, it is considered somewhat “bad form” as the EVENT constants (i.e. TimerEvent.TIMER)won’t be depreciated in future versions of AS, while “timer” might be. Thanks for the write-up!
January 4th, 2010 at 7:59 am
I have been looking for a simple time delay in ActionScript, and I found this one useful. I think it is easy and simple to understand how to use it.