Using the Timer class in ActionScript 3.0

Another great new addition in ActionScript 3.0 is the Timer class (flash.utils.Timer), which essentially replaces the setInterval() and setTimeout() methods in ActionScript 2.0. For example, here’s an example of the setTimeout() method in ActionScript 2.0:

// AS2
var intID:Number = setTimeout(runOnce, 1000); // 1 second
function runOnce():Void {
trace("runOnce() called @ " + getTimer() + " ms");
}

In ActionScript 3.0, the same code could be rewritten as follows:

// AS3
var myTimer:Timer = new Timer(1000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runOnce);
myTimer.start();

function runOnce(event:TimerEvent):void {
trace("runOnce() called @ " + getTimer() + " ms");
}

Note that the Timer() constructor takes two parameters. The first parameter controls how frequently the TimerEvent.TIMER event gets dispatched (in milliseconds). The second parameter is the number of times that the TimerEvent.TIMER event will be dispatched before stopping. In this example, the timer will dispatch only once before quitting. If you set the second parameter to 0 (zero) or omitted it completely, the timer would run forever (or until you called the stop() method on the timer instance.

If you wanted the code to continuously run in ActionScript 2.0, you would use the setInterval() method instead of the setTimeout() method, as seen in the following example:

// AS2
var intID:Number = setInterval(runMany, 1000); // 1 second
function runMany():Void {
trace("runMany() called @ " + getTimer() + " ms");
}

The previous code snippet would continue to run until the interval was stopped by calling the clearInterval() method and passing in the interval id (which was saved in the variable intID). The same code could be rewritten in ActionScript 3.0 as follows:

// AS3
var myTimer:Timer = new Timer(1000); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runMany);
myTimer.start();

function runMany(event:TimerEvent):void {
trace("runMany() called @ " + getTimer() + " ms");
}