design. business. life.

Information

This article was written on 17 Jul 2009, and is filled under Flash.

Current post is tagged

, , , ,

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!

3 Comments

  1. lovebolivia
    July 28, 2009

    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. parker
    December 8, 2009

    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!

  3. Nathanael Yoshi
    February 8, 2012

    I’m normally to blogging and i genuinely appreciate your posts. The write-up has truly peaks my interest. I am going to bookmark your internet site and keep checking picking out particulars.

Leave a Reply