ActionScript 3 introduces a new class to ActionScript called the Timer class (flash.utils.Timer). This class is kind of like a suped-up setInterval (flash.utils.setInterval()) that sends event messages out over a period of time measured in milliseconds. Because it uses events (flash.events.TimerEvent) and not a callback like setInterval, a single Timer instance can be used to call many different functions as long as they are made listeners of that instance. Additionally, Timer gives you the ability to control how many times it repeats, unlike setInterval which repeats indefinitely until clearInterval is used to shut it down, as well as the ability to start and stop the timer on command.
Example:
ActionScript Code:
var timer:Timer = new Timer(500, 10);
timer.addEventListener(TimerEvent.TIMER, notifier);
timer.addEventListener(TimerEvent.TIMER, stopper);
stage.addEventListener(MouseEvent.CLICK, continuer);
function notifier(event:TimerEvent):void {
trace(timer.currentCount);
}
function stopper(event:TimerEvent):void {
switch (timer.currentCount) {
case 5:
timer.stop();
break;
case timer.repeatCount:
timer.reset();
break;
}
}
function continuer(event:MouseEvent):void {
timer.start();
}
timer.start();
This timer instance sends a TimerEvent.TIMER event every 500 milliseconds and repeats 10 times. There are 2 event listeners responding to these events, one tracing the current count of the timer and the other which will either stop (on current count of 5) or reset the timer (on current count of total count) based on the timer's current count. A mouse click to the stage will allow you to restart the timer as a result of it being stopped in the stopper listener. What you end up getting is
Code:
1
2
3
4
5
(pause; click to continue)
6
7
8
9
10
(pause; click to continue)
1
2
3
4
5
...

0 评论:
发表评论