Archive

Posts Tagged ‘Timer class’

Building a simple clock application in as3

February 25th, 2009

Yesterday I posted how the Date class worked in ActionScript 3.  Today I though I would build a simple clock application using the Date class.

Building the clock app involves using the Date class in a couple of ways. The Date class returns the current date and time of when the method is called and only once per object created. Basically the example I gave in my previous Date class post performed this once.

To have our clock continually roll through the time and date, a new Date object must be created and the methods of the Date class that return the date and time properties must be called at regular intervals to display the changing time. To create our clock application, we will use the Timer class.

The following code will create a TextField object to display the time and a Timer object that updates every 1/10th of a second in the updateTime() event handler for the Timer event of the Timer class.

When the updateTime() event handler is called on each TIMER event, a new Date object and a new variable for the time are created, concatenated, and set as the text property for myDisplay.

A new Date object needs to be created each time because the Date class stores only the time and date values for the time in which the object was created.

Alright.. Let's get into the code..

var myDisplay:TextField = new TextField();
var myTimer:Timer = new Timer(100);
 
myTimer.addEventListener(TimerEvent.TIMER, updateTime);
 
function updateTime(evt:TimerEvent):void{
 
var localDate:Date = new Date();
var hour:int = localDate.getHours();
var minute:String;
var second:String;
 
/* Note that if the second and minute
values are less than 10 we add a 0 to the
single digit */
 
if(localDate.getMinutes()<10){
	minute = String(0)+localDate.getMinutes();
}else{
	minute = String(localDate.getMinutes());
}
 
if(localDate.getSeconds()<10){
	second = String(0)+localDate.getSeconds();
}else{
	second = String(localDate.getSeconds());
}
 
myDisplay.text = hour+':'+minute+':'+second;
 
}
 
myTimer.start();
addChild(myDisplay);

Hope this helps ...  Peace...

Post to Twitter Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

Flashnutz ActionScript 3.0 , , , ,

SEO Powered by Platinum SEO from Techblissonline