package {
import flash.events.TimerEvent;
import flash.utils.Timer;
public class CountdownTimer extends Timer {
public var time:Number = 0;
public function CountdownTimer(time:Number = Number.NEGATIVE_INFINITY, delay:Number = 1000) {
super(delay, repeatCount);
if (!isNaN(time))
this.time = time;
repeatCount = Math.ceil(time / delay);
addEventListener(TimerEvent.TIMER, timerHandler);
addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
}
override public function start():void {
super.start();
}
protected function timerHandler(event:TimerEvent):void {
time -= delay;
}
protected function timerCompleteHandler(event:TimerEvent):void {
}
override public function stop():void {
super.stop();
}
public function dispose():void {
removeEventListener(TimerEvent.TIMER, timerHandler);
removeEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
}
}
}
This CountdownTimer
extends Timer
, and is used exactly the same, except that time counts down.
Example usage:
var timer:CountdownTimer = new CountdownTimer(5000);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, completeHandler);
timer.start();
function timerHandler(event:TimerEvent):void {
trace("Time remaining: " + event.target.time);
}
function completeHandler(event:TimerEvent):void {
trace("Timer complete");
}
Above example would output:
[trace] Time remaining: 4000
[trace] Time remaining: 3000
[trace] Time remaining: 2000
[trace] Time remaining: 1000
[trace] Time remaining: 0
[trace] Timer complete