Pages

Sunday, July 18, 2010

AS3 Timer - ActionScript 3 Tutorial | Introduction to the Flash ActionScript 3.0 Timer Class

The Flash AS3 Timer class lets you create Timer objects, one common usage of which would be to create counters for your Flash application - like an AS3 countdown timer, a time limit counter for a game or some sort of timer delay. In this tutorial, we'll learn the basics of working with the Timer ActionScript 3 class.

NOTE: For those of you coming from AS2 and have been using the setInterval() function - there is also an AS3 setInterval() function, but the AS3 Timer class is a good alternative to using setInterval().

A Timer object has the ability to count at a specific interval, which can be set using what is called the delay. The delay is specified in milliseconds. For example, if there is a delay of 1000 milliseconds, then the Timer object will count at 1 second intervals. If there is a delay of 5000 milliseconds, then the Timer counts every 5 seconds. You can specify a delay as short as 20 milliseconds, but anything lower than that is not recommended and may cause problems.

So now let's go ahead and create a new AS3 Timer object. The Timer ActionScript 3 constructor accepts 2 parameters. The first parameter is for the delay. The second parameter is for the repeatCount. The repeatCount specifies the number of repetitions the Timer will make. If you don't specify a repeatCount or if you specify zero, the timer repeats indefinitely. If you specify a positive nonzero value, then the timer runs at that specified number of times and then stops. So for example, if you specify a repeatCount of 5, then the Timer will count 5 times and then stop. The delay parameter is required, while the repeatCount is optional.
var myTimer:Timer = new Timer(1000);

This creates a new Timer object named myTimer. A delay of one second has been specified.

NOTE: The delay is not always 100% accurate. It will usually be off by a few milliseconds, but in many cases, it's barely noticeable.

The Timer will not start automatically. Use the start() method of the Timer class in order to tell the Timer object to start.
var myTimer:Timer = new Timer(1000);
myTimer.start();

If you test your movie now, the Flash movie will launch, but you won't see anything happen. In order to tell Flash to respond and do something, then we'll need to create AS3 Timer event handlers so that our Flash movie will know what to do when certain Timer associated events get dispatched.

Let's first take a look at the TimerEvent.TIMER event. This event gets dispatched every time the Timer object makes a count. So for example, if you have a Timer object that has a 1 second delay, then TimerEvent.TIMER will get dispatched every 1 second. This event is useful if you'd like your Flash movie to do something repeatedly at a constant interval. So let's go ahead and create a TimerEvent.TIMER event handler that will tell Flash to display the word hello in the output window every time the Timer makes a count.
var myTimer:Timer = new Timer(1000);
myTimer.start();

myTimer.addEventListener(TimerEvent.TIMER, sayHello);

function sayHello(e:TimerEvent):void {
     trace("hello");
}

So now, if you test the movie, you will see the word hello come out in the output window every 1 second.

If you wish to keep track of how many times the Timer has been counting, then you can use the currentCount property of the Timer class. Each time the Timer makes a count, the currentCount property increases by 1. Let's add a trace statement that's going to output the Timer object's currentCount value every time the Timer makes a count.
var myTimer:Timer = new Timer(1000);
myTimer.start();

myTimer.addEventListener(TimerEvent.TIMER,  sayHello);

function sayHello(e:TimerEvent):void 
{
     trace("hello");
     trace("Current Count: " + myTimer.currentCount);
}

NOTE: The currentCount property begins at 0, but when you test the movie, you will see that the first value displayed is 1. This is because the Timer will only begin dispatching TimerEvent.TIMER after it makes that first count from 0 to 1. Also note that if you stop the Timer and then start it again, the currentCount will continue counting from that last value that it stopped at. To reset the currentCount property of a Timer object back to 0, then you can use the reset() method of the Timer class ( ex. myTimer.reset(); ). If the Timer is running, then the reset() method will also stop the Timer.

The other event that gets dispatched by the AS3 Timer object is the TimerEvent.TIMER_COMPLETE event. This gets dispatched when the Timer has completed the number of counts as set by the repeatCount parameter.

So let's go ahead and add in a repeatCount of 10, and then let's create an event handler for the TimerEvent.TIMER_COMPLETE event. Let's tell the Flash movie to output the word bye once it completes the specified number of counts.
var myTimer:Timer = new Timer(1000, 10);
myTimer.start();

myTimer.addEventListener(TimerEvent.TIMER, sayHello);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, sayBye);

function sayHello(e:TimerEvent):void 
{
     trace("hello");
     trace("Current Count: " + myTimer.currentCount);
}

function sayBye(e:TimerEvent):void 
{     
     trace("bye");
}

So in the example above, the Timer will count 10 times. Each time it makes a count, the word hello will come out in the output window, and the currentCount value will increase by 1. Once it reaches 10, then the TimerEvent.TIMER_COMPLETE event gets dispatched, and you will see the word bye come out in the output window.

And that concludes this AS3 Timer - ActionScript 3 tutorial.

6 comments:

  1. good synopsis
    to the point and simple

    i've been trying to build a metronome
    but have the feeling that it would
    not be possible to build an exact one
    because it would be different for each platform
    and connection

    tzon@ptd.net

    ReplyDelete
  2. that great!

    I have a question, can I pass a parameter in the timer function.
    Something like

    myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, sayBye, paameter);

    function sayBye(e:TimerEvent, paameter):void

    ReplyDelete
  3. Not that way, unless you create a custom class. But you might want to take a look at this: Passing parameters to AS3 event handlers

    ReplyDelete
  4. The tutorial is as beautiful as it is precise, concise and simple. :-)

    P.S. How would you combine displaying a message for a given time with a rollover?

    ReplyDelete
  5. Hi, I'm planning to create an interactive music video. Can this method be used? Like say import a video 5 seconds after the button is clicked? Please advice thanks.

    ReplyDelete
  6. Hi,
    I'm using a simple script on my project and I want it to start flipping automatically. So basically I've just used those lines of code:
    import com.greensock.*;
    import com.greensock.easing.*;

    flipper.sideB.rotationY = -90;
    flipper.sideB.alpha=0;


    var flipSpeed:Number = .5;


    var tl:TimelineMax = new TimelineMax();
    tl.append(TweenMax.to(flipper.sideA, flipSpeed, {rotationY:90, visible:false, ease:Linear.easeNone}))
    tl.append(TweenMax.to(flipper.sideB, 0, {alpha:1, immediateRender:false}));
    tl.append(TweenMax.to(flipper.sideB, flipSpeed, {rotationY:0, ease:Linear.easeNone}))

    How can I use AS3 Timer for 1s delay?
    My project has 12 fps

    ReplyDelete