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!

4 Responses to “Timer Delay in Actionscript 3.0”

  1. lovebolivia Says:

    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.

  2. Radiant Barrier Houston Says:

    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.

  3. parker Says:

    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!

  4. tiensshop Says:

    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.

Leave a Reply

This entry was posted on Friday, July 17th, 2009 at 1:21 am and is filed under Flash Design & Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.