Below, we have an example program, which creates a timer callback function. This program draws a circle that flashes in the middle of the screen at a rate that is specified by the timer that we create. The code sets a timer to call a function that, alternatively, adds and removes a circle from the objects that are to be displayed.
The first three lines of active code initialize the Timer. The first line creates an instance of a Timer that creates a TIMER event every 1000 milliseconds, which equals 1 second. The second line sets the function FlashCircle() to get called every time a TIMER event occurs. The third line starts the Timer so that it generates events every second.
// Create a 1 second timer
var qMyTimer:Timer = new Timer(1000);
qMyTimer.addEventListener(TimerEvent.TIMER, FlashCircle);
qMyTimer.start();
var bDrawCircle:Boolean = true;
// Create a sprite with a circle drawn on it.
var qCircle:Sprite = new Sprite();
var uiColor:uint = 0x00800000;
qCircle.graphics.beginFill(uiColor);
qCircle.graphics.drawCircle(160, 120, 100);
qCircle.graphics.endFill();
function FlashCircle(e:TimerEvent):void {
// Add or remove the circle from the stage
if (bDrawCircle) {
addChild(qCircle);
} else {
removeChild(qCircle);
}
// Alternate the drawing
bDrawCircle = !bDrawCircle;
}
Once the timer is initialized, we have a Boolean, bDrawCircle, that is used to toggle the display of the circle. Below this, we create a Sprite and draw a dark red circle on it. The circle is located at (160, 120) and has a radius of 100.
Finally, we have the callback function FlashCircle(). This function is called every second via a TIMER event. Inside the function, we add or remove the Sprite with the circle drawn on it from the list of items to be displayed. The last line reverses the value of the Boolean, bDrawCircle, to alternate it value between true and false and toggle the drawing of qCircle.
var qMyTimer:Timer = new Timer(1000, 3);
The timer in the program runs continuously. We could set the second argument in the constructor to 3, as shown in the line above. With this constructor call, the timer only runs 3 seconds and generates 3 events. When we don’t specify a second argument, the default value of 0 is used, which sets the timer to run indefinitely.
When we have a finite number of events coming from the timer, we can set an event callback to run when the timer is completely finished. The event TimerEvent.TIMER_COMPLETE can be used instead of TimerEvent.TIMER for a callback that runs when the timer is completely finished.