Timer Class in Actionscript 3.0
I have been playing with the Timer Class in Actionscript 3.0. It replaces setInterval from AS2. It seems to work about the same. It is a bit more robust; you quite a bit more control over it. Here is a sample of code I have been testing:
_myTimer = new Timer(_delay, _repeatCount);
// _repeatCount is optional, if no value then it do the Timer forever
_myTimer.addEventListener(TimerEvent.TIMER, timerHandler);
_myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, completeHandler);
_myTimer.start();
private function timerHandler(e:TimerEvent):void{
lastIndex=curIndex;
trace(lastIndex: "+lastIndex);
curIndex+=1;
trace("curIndex: "+curIndex);
}private function completeHandler(e:TimerEvent):void {
//complete after _repeatCount is complete;
//kill listeners for garbage collection
_myTimer.removeEventListener(TimerEvent.TIMER, timerHandler);
_myTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, completeHandler);
// null out _myTimer only if you want to
// completely remove the timer
_myTimer = null
}
Now, the timer works fine by itself, but when you add interaction with it such as a button, you need to use a little care on how you stop or kill the timer so it doesn't interfere with the button interaction. I found that _myTimer.stop()works well if you want to eventually restart the Timer. I have further testing to do where if I completely remove the Timer listener and set _myTimer=null (for garbage collection), I hit errors that do not allow for me to allow for the same interaction any longer. I'm sure it is a bug of my own creation, but as I am still figuring this new syntax out, I will be doing numerous experiments to perfect this little issue.


