AS2 → AS3: Running Actions On Intervals
The new Timer class in AS3 gives you the ability to create and run actions at set intervals, much like the setInterval in AS2. The difference, however, is that now you can define how many times the timer runs right within the constructor. Let's take a look at the old, haggish way to do it in AS2:
-
var t:Number = setInterval(traceMessage, 1000);
-
var count:Number = 0;
-
-
function traceMessage():Void
-
{
-
if (count <10)
-
{
-
count++;
-
-
trace("This is running once every second.");
-
}
-
else
-
{
-
clearInterval(t);
-
-
trace("The timer has traced out ten times.");
-
}
-
}
And now the new, improved, sexy way to do it in AS3:
-
var t:Timer = new Timer(1000, 10);
-
t.addEventListener("timer", traceMessage);
-
t.addEventListener("timerComplete", traceFinishedMessage);
-
t.start();
-
-
function traceMessage($evt:TimerEvent):void
-
{
-
trace("This is running once every second.");
-
}
-
-
function traceFinishedMessage($evt:TimerEvent):void
-
{
-
trace("The timer has traced out ten times.");
-
}
As you can see, the Timer constructor takes in two parameters. The first is the time, in milliseconds, that each interval should run on (in this case, 1000 ms = 1 sec), and the second is the number of times that the action should repeat.
If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.











In AS2 you have the clearInterval. When running the timer event class in your traceFinishedMessage method would you want to remove the EventListener?
function traceFinishedMessage($evt:TimerEvent):void
{
t.removeEventListener("timer", traceMessage);
trace("The timer has traced out ten times.");
}