Thursday, July 9, 2009

Adobe Flex: Creating a countdown clock with Timer

Are you trying to find a quick and easy way of creating a countdown clock in Adobe Flex. Don't look any further. I'll go straight to the point:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
[Bindable]
private var n_seconds_left:int=30;
private var timer:Timer;

/**
* Initialises the timer
*/
private function creationComplete():void {
this.timer= new Timer(1000,n_seconds_left);
timer.addEventListener(TimerEvent.TIMER,decrementSeconds);
timer.start();
}

/**
* Decrements the number of seconds left if it still is
* bigger than 0. Otherwise stop the timer.
*
*/
private function decrementSeconds(event:TimerEvent):void {
n_seconds_left--;
}

]]>
</mx:Script>
<mx:Label text="Final Countdown: {n_seconds_left}" fontSize="18"/>
</mx:Application>


The constructor for the Timer class in Adobe Flex takes two arguments:

  1. delay- Time interval in milliseconds for generating a TimerEvent. In our example, we set that value as 1000 milliseconds=1 second as you would expect for a clock.
  2. count - number of times that a TimerEvent will be generated before a TimerEvent.TIME_COMPLETE is generated. In our example it was 30. This means that our countdown clock only runs for 30 seconds. If you don't specify this value the Timer will run forever and the TimerEvent.TIME_COMPLETE will never be dispatched


If we don't specify the second argument when creating a Timer we still can achieve the same results:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
[Bindable]
private var n_seconds_left:int=30;
private var timer:Timer;

/**
* Initialises the timer
*/
private function creationComplete():void {
this.timer= new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, decrementSeconds);
timer.start();
}

/**
* Decrements the number of seconds left if it still is
* bigger than 0. Otherwise stop the timer.
*
*/
private function decrementSeconds(event:TimerEvent):void {
if (this.n_seconds_left>0) {
n_seconds_left--;
}
else {
timer.stop();
}
}

]]>
</mx:Script>
<mx:Label text="Final Countdown: {n_seconds_left}" fontSize="18"/>
</mx:Application>


The biggest difference to the previous code is that we use Timer.stop() to interrupt the timer to prevent another TimerEvent from being called so that our countdown clock doesn't go below 0.

Click here to see our countdown clock in action

No comments:

 
Software