In previous version of ActionScript there were a couple of different ways to trigger events based on time. The setInterval() and setTimeout() functions were the two most commonly used ways of calling a function after a specified amount of time had lapsed. In ActionScript 3 we now have the Timer class which lives in theflash.utils package. This class contains all the functionality that you will ever need for time-based applications. In order to use the class, you first must import the flash.utils package as seen is the example below. The Timer constructor expects one argument that represents the desired delay in milliseconds between function calls. An optional seconds argument determines the number of times to call the function. The default for this value is 0, which means that it will call the function indefinitely. If you wanted to replicate the functionality of the deprecated setTimeout() function, you can simply pass 1 as the value for this parameter.
In my example below I am creating a Timer that will fire twice a second, but I haven’t yet told it what function to call every time the delay has passed. To do this we need to respond to the timer event of the Timer class and give it the name of the function that will handle the event. At this point our Timer will be setup for use but we still need to call the Timer.start() method in order to get things started. In my implementation below I am simply doing a trace() to the output window every time the Timer fires showing how many times it has fired. To get this value I am reading the Timer.currentCount property.
[as]// We need to import the utils package
import flash.utils.*;
// Create a new Timer object with a delay of 500 ms
var myTimer:Timer = new Timer(500);
myTimer.addEventListener(“timer”, timedFunction);
// Start the timer
myTimer.start();
// Function will be called every 500 milliseconds
function timedFunction(eventArgs:TimerEvent)
{
trace(“Timer fired ” + myTimer.currentCount + ” times.”);
}[/as]
Check out the AS 3 docs to see all of the available properties and methods of this great new class.