AS2 → AS3: Running Actions On Intervals

Download Example Files

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:

Actionscript:
  1. var t:Number = setInterval(traceMessage, 1000);
  2. var count:Number = 0;
  3.  
  4. function traceMessage():Void
  5. {
  6.     if (count <10)
  7.     {
  8.         count++;
  9.        
  10.         trace("This is running once every second.");
  11.     }
  12.     else
  13.     {
  14.         clearInterval(t);
  15.        
  16.         trace("The timer has traced out ten times.");
  17.     }
  18. }

And now the new, improved, sexy way to do it in AS3:

Actionscript:
  1. var t:Timer = new Timer(1000, 10);
  2. t.addEventListener("timer", traceMessage);
  3. t.addEventListener("timerComplete", traceFinishedMessage);
  4. t.start();
  5.  
  6. function traceMessage($evt:TimerEvent):void
  7. {
  8.     trace("This is running once every second.");
  9. }
  10.  
  11. function traceFinishedMessage($evt:TimerEvent):void
  12. {
  13.     trace("The timer has traced out ten times.");
  14. }

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.

2 Comments

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.");
}

i thought about adding that in there and although i didn't, its probably a good idea to do your own garbage collection. good call.

Leave a comment

(required)

(required)