Friday, July 9, 2010

How to make a digital clock using Actionscript 3

Have you ever wanted to make your own digital clock? Today we are going to learn how to create one in Flash. Here's how our final product will look like:

Some people would just create a text area and then make it update every frame to show the time on your SysTray. However, that is a bad way to do it - Flash needs to go to the System every time to change the time.

Instead of that, we will ask the System about time just once, in the very beginning. Then we will just add to it every second. Here is the commented code:
var now:Date = new Date();// getting date
var everySecond:Timer=new Timer(1000);// 1000 milliseconds = 1 second

var hours=now.hours;// setting time on start
var minutes=now.minutes;
var seconds=now.seconds;

var hourStr:String;// creating new strings to add zeros to (if needed)
var minStr:String;
var secStr:String;

everySecond.start();// start the timer, it's show time

function doClock() {
 // the code below adds "0" in front of the numbers if needed
 /*This is just like an if...else statement, but shortened. Here is
 the syntax: (expression) ? istrue : isfalse*/
 timeTextField.text=hourStr+":"+minStr+":"+secStr;// update text field

function update(TimerEvent):void {
 seconds++; // update and add a second
 if(seconds==60){ // correcting numbers if they reach maximum

everySecond.addEventListener(TimerEvent.TIMER, update);// calls function update every second

doClock(); // call the function on start

There you have it, a working clock in Flash!

Using this code, you can also create alarm clocks, reminders, etc.


Anthony said...

What if you wanted miliseconds to be displayed also

Anonymous said...

How would I integrate this into the calendar with an alarm function?

Dheeraj Rawat said...

nice, thank u

Post a Comment