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"
    import mx.binding.utils.BindingUtils;
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    public var timerInterval:int = 100;
    public var maxSeconds:uint = 10;

    public var pattern:String = "N:SS";

    public var warningSeconds:uint = 5;
    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;
        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();

    public function stopTimer():void {

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


And, a silly little test application…

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

    import mx.controls.Alert;
    private function timeExpired(event:Event):void {
      Alert.show( "Yo!  Times Up!" );

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

  <local:CountdownTimer id="counter" fontSize="96" 
                           pattern="Time Remaining: N:SS"