Friday, September 3, 2010

All about Timer class in Actionscript 3

Today is all about timers!

Timer class is often very useful in Actionscript 3, that's why it is important to know everything about it.

Timer has 2 parameters - delay and repeatCount. Think of it as of a clock, that has one Arrow that moves 'repeatCount' times every 'delay' milliseconds. If we set repeatCount to 0, our Timer will keep firing forever.

The code below creates a Timer with an interval of 1000 milliseconds (1 second) that repeats 3 times:

var myTimer:Timer = new Timer(1000, 3);

We created our Timer, but we didn't start it yet.

myTimer.start();

Now let's trace a message every time our Timer makes a cycle:

myTimer.addEventListener(TimerEvent.TIMER, timerFunction);
function timerFunction (e:TimerEvent):void{
trace("Current count: " + myTimer.currentCount);
}

Now if we test our movie, we will see that our output window updates every second for 3 seconds and show how many times has the Timer made a cycle.

We can also set the repeatCount and delay after we create our Timer:

myTimer.delay=500
myTimer.repeatCount=5

We can check whether the Timer is active right now. It is a read-only parameter, just like currentCount.

trace(myTimer.running); // Returns true or false

We are able to reset our Timer. Resetting a timer stops it and sets its currentCount to 0.

myTimer.reset();

We can, of course, stop our timer manually too.

myTimer.stop();

We can create a listener for an event that will happen once the timer's currentCount equals repeatCount. Here's how:

myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerComplete);
function timerComplete (e:TimerEvent):void{
trace("Time's up!");
}

That's all you need to know to start using this useful class! Timers can be used for many things, for example, creating digital clocks or a typewriter effect.

Thanks for reading!

No comments:

Post a Comment