May 14

It’s been a while since my last post. My connection has been down for a few days, so I haven’t got the chance to post. But during this downtime, I found some time to create some experiments in Flash/AS3.0 (maybe I’ll post it soon). I needed to call a method at timed intervals in this one experiment, and I thought I was in trouble. I never got around to getting how AS2.0 handled timers, if I did manage to do timers, they end up dirty.

AS3.0 has a much much better Timer class to handle just such events. Now, I’m not going to bother comparing the AS3 Timer class with AS2’s timer handling, I’m just going to give a quick intro to the class.

First, you need to create a new Timer object. The constructor has 2 parameters, delay and repeatCount. delay is the time in milliseconds the intervals will be. repeatCount is the number of times the Timer will run, assigning it 0 will set it to run infinitely.

[sourcecode language='jscript']
var myTimer:Timer = new Timer(1000, 5);
[/sourcecode]

Now, we want to write a function that will get called when an interval is passed (every 1 second), and when the whole timer finishes counting (after 5 seconds). The Timer class dispatches two events, TimerEvent.TIMER is dispatched when an interval is passed, TimerEvent.TIMER_COMPLETE is dispatched when the timer is finished (I love how simple that is).

[sourcecode language='jscript']
stage.addEventListener(TimerEvent.TIMER, everySecond);
stage.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);

function everySecond(e:TimerEvent):void{
trace(”tick tock!”);
}
function onComplete(e:TimerEvent):void{
trace(”Timer finished!”);
}
[/sourcecode]

Now, we just need to start the timer. The Timer class has 3 methods, start, stop, and reset. Those are fairly self-explanatory. We could now add the following lines:

[sourcecode language='jscript']
myTimer.start();
//modify the onComplete function
function onComplete(e:TimerEvent):void{
trace(”Timer finished!”);
myTimer.reset();
myTimer.start();
}
[/sourcecode]

So now, when our timer finishes, it will automatically start all over again. This will trace
[sourcecode language='js']
tick tock!
tick tock!
tick tock!
tick tock!
tick tock!
Timer finished!
tick tock!
tick tock!

[/sourcecode]

This was just a really quick intro to the Timer class, I just felt like sharing this because I was so relieved at how easy it was to handle timed events now.


leave a reply