Wednesday, December 8, 2010

Create a timer application using AS3

Today we'll create a timer.

See how it works:


First of all, put a text field on stage, name it txt_timer. Add 2 buttons, labelled Start (bt_start_stop) and Reset (bt_reset). Add 6 more buttons (arrows in my example) that will increase/decrease the number of seconds/minutes/hours. Name them bt_secs_down, bt_secs_up, bt_mins_down, bt_mins_up, bt_hrs_down, bt_hrs_up.

Now, the code! If you have read my previous tutorial on making a stopwatch, you'll see some similar parts. Anyway, here is the code. It is complex, but quite simple.

import flash.utils.Timer;
updateTime();

var t_hrs:int = 0;
var t_mins:int = 0;
var t_secs:int = 0;

function updateTime():void
{
txt_time.text = "";
txt_time.appendText((t_hrs>9)?(t_hrs.toString()):("0"+t_hrs.toString()));
txt_time.appendText(":");
txt_time.appendText((t_mins>9)?(t_mins.toString()):("0"+t_mins.toString()));
txt_time.appendText(":");
txt_time.appendText((t_secs>9)?(t_secs.toString()):("0"+t_secs.toString()));
}

var mainTimer:Timer = new Timer(1000);
mainTimer.addEventListener(TimerEvent.TIMER, timerUpdate);

function timerUpdate(TimerEvent):void
{
if (t_secs == 0 && t_mins == 0 && t_hrs == 0)
{
mainTimer.stop();
bt_start_stop.label = "Start";
}
else
{
t_secs--;
if (t_secs < 0 && (t_mins > 0 || t_hrs > 0)){
t_secs = 59;
}
if (t_secs == 0 && t_mins > 0)
{
t_secs = 59;
t_mins--;
}
if (t_mins == 0 && t_hrs > 0)
{
t_mins = 59;
t_hrs--;
}
}
updateTime();
}

bt_start_stop.addEventListener(MouseEvent.CLICK, startTimer);

function startTimer(MouseEvent):void
{
if (bt_start_stop.label == "Start")
{
mainTimer.start();
bt_start_stop.label = "Stop";
}
else if (bt_start_stop.label == "Stop")
{
mainTimer.stop();
bt_start_stop.label = "Start";
}
}

bt_reset.addEventListener(MouseEvent.CLICK, resetTimer);

function resetTimer(MouseEvent):void
{
t_secs = 0;
t_mins = 0;
t_hrs = 0;

updateTime();
}
bt_secs_down.addEventListener(MouseEvent.CLICK, buttonManager);
bt_secs_up.addEventListener(MouseEvent.CLICK, buttonManager);
bt_mins_down.addEventListener(MouseEvent.CLICK, buttonManager);
bt_mins_up.addEventListener(MouseEvent.CLICK, buttonManager);
bt_hrs_down.addEventListener(MouseEvent.CLICK, buttonManager);
bt_hrs_up.addEventListener(MouseEvent.CLICK, buttonManager);

function buttonManager(evt:MouseEvent):void
{
if (evt.target.name == "bt_secs_down")
{
t_secs--;

if (t_secs < 0)
{
t_secs = 59;
}
}
else if (evt.target.name == "bt_mins_down")
{
t_mins--;

if (t_mins < 0)
{
t_mins = 59;
}
}
else if (evt.target.name == "bt_hrs_down")
{
if (t_hrs > 0)
{
t_hrs--;
}
}
else if (evt.target.name == "bt_secs_up")
{
t_secs++;

if (t_secs > 59)
{
t_secs = 0;
}
}
else if (evt.target.name == "bt_mins_up")
{
t_mins++;

if (t_mins > 59)
{
t_mins = 0;
}
}
else if (evt.target.name == "bt_hrs_up")
{
t_hrs++;
}

updateTime();
}

Thanks for reading!

No comments:

Post a Comment