Google analytics code

Monday, August 10, 2009

Flex: setTimeout and setInterval replacement

One of the things I learned while moving from AS2 to AS3 is that setTimeout no longer exists. It's been replaced with a Timer class. It can be used like setTimeout or setInterval.

This is how you would use Timer as a setTimeout. The variable tTimer is set to launch 500 ms after start() is run. It will run once and then stop.

import flash.events.TimerEvent;
import flash.utils.Timer;

private function Timer_example()
{
var tTimer:Timer = new Timer(500, 1);
tTimer.addEventListener(TimerEvent.TIMER, onTimer);
tTimer.start();
}
private function onTimer(event:TimerEvent)
{
trace('callback event has run');
}


Timer can also function like setInterval. The second parameter tells timer how many times it should run. So if you want something to run 100 times then set timer will look like this.

var tTimer:Timer = new Timer(500, 100);

If you want it to run forever then set the interval to 0. If you do this make sure the timer is a global variable so you can run .stop() when it no longer needs to run.

2 comments:

  1. Thanks. Right up there at the top of results when you search for "Flex Timer", which I was discovering how to use.

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.