Posts Tagged ‘Timer object’

Building a simple clock application in as3

February 25th, 2009 3 comments

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..

  1. var myDisplay:TextField = new TextField();
  2. var myTimer:Timer = new Timer(100);
  4. myTimer.addEventListener(TimerEvent.TIMER, updateTime);
  6. function updateTime(evt:TimerEvent):void{
  8. var localDate:Date = new Date();
  9. var hour:int = localDate.getHours();
  10. var minute:String;
  11. var second:String;
  13. /* Note that if the second and minute
  14. values are less than 10 we add a 0 to the
  15. single digit */
  17. if(localDate.getMinutes()<10){
  18. minute = String(0)+localDate.getMinutes();
  19. }else{
  20. minute = String(localDate.getMinutes());
  21. }
  23. if(localDate.getSeconds()<10){
  24. second = String(0)+localDate.getSeconds();
  25. }else{
  26. second = String(localDate.getSeconds());
  27. }
  29. myDisplay.text = hour+':'+minute+':'+second;
  31. }
  33. myTimer.start();
  34. addChild(myDisplay);

Hope this helps ...  Peace...

SEO Powered by Platinum SEO from Techblissonline