Flex Countdown Timer with Warning Color/Expiration Event


I had to create a simple little Flex countdown timer, so I stumbled upon thie post from Flex Examples. I took that source and expanded it a bit to create a configurable CountdownTimer component. Now, I’m sure there’s an even easier way to do this, but this seems to do the job for me. Here’s the result CountdownTimer.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Label xmlns:mx="http://www.adobe.com/2006/mxml"
        creationComplete="init()">
  <mx:Metadata>
    [Event(name="timesUp",type="flash.events.Event")]
  </mx:Metadata>
  <mx:Script>
    <![CDATA[
    import mx.binding.utils.BindingUtils;
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    [Binable]
    public var timerInterval:int = 100;
            
    [Bindable]
    public var maxSeconds:uint = 10;

    [Bindable]
    public var pattern:String = "N:SS";

    [Bindable]
    public var warningSeconds:uint = 5;
                                                                   
    [Bindable]
    public var warningColor:uint = 0xff0000;

    private var baseTimer:int;

    private var t:Timer;

    private function init():void {
      t = new Timer(timerInterval);
      t.addEventListener(TimerEvent.TIMER, updateTimer);
    }

    private function updateTimer(evt:TimerEvent):void {
      var renderTime:int = ((maxSeconds * 1000) - (getTimer() - baseTimer));
      if( renderTime <= 0 ) {
        renderTime = 1;
        t.stop();       
        dispatchEvent( new Event("timesUp",true) );
      }
                                                   
      var seconds:int = renderTime / 1000;
      if( seconds < warningSeconds ) {
        this.setStyle("color", warningColor );
      }
                                                                    
      var d:Date = new Date(renderTime);
      this.text = dateFormatter.format(d);
    }

    public function startTimer():void {
      baseTimer = getTimer();
      t.start();
    }

    public function stopTimer():void {
      t.stop();
    }
  ]]>
  </mx:Script>

  <mx:DateFormatter id="dateFormatter" formatString="{pattern}" />

</mx:Label>

And, a silly little test application…

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        xmlns:local="*">

  <mx:Script>
  <![CDATA[
    import mx.controls.Alert;
    private function timeExpired(event:Event):void {
      Alert.show( "Yo!  Times Up!" );
  ]]>
  </mx:Script>

  <mx:ApplicationControlBar dock="true">
    <mx:Button label="Start timer" click="counter.startTimer()" />
    <mx:Button label="Stop timer" click="counter.stopTimer()" />
  </mx:ApplicationControlBar>

  <local:CountdownTimer id="counter" fontSize="96" 
                           pattern="Time Remaining: N:SS" 
                           timesUp="timeExpired(event)"/>
</mx:Application>