Tuesday, December 7, 2010

Create a stopwatch using AS3

Today we'll make a fully functional stopwatch.

Before we do anything, try it out:


Place one text field (txt_time) on the stage, a list component (list_history) and 5 buttons - Start (bt_start), New Lap (bt_lap), Stop (bt_stop), Reset (bt_reset) and Continue (bt_continue).

To create a stopwatch, we'll need 4 variables to store the time data - t_hrs, t_mins, t_secs and t_msecs. We'll need a function (updateTime()), which manages the display of the time. For example, if t_secs equals 3, the piece of text responsible for second will have to display "03" instead of just "3".

We'll need an Array to store the lap history data. We'll make changes to it and then update the list's data provider object to this array.

Of course, we'll need a Timer. The timer's delay will be 100 and with each lap it will add 100 milliseconds (in reality, it will add 1 and then add zero after it). If you want, you can set the delay to 10 and add 10 millisecond with every loop, but that won't work too good, just think about it - your machine will need to do all the computing every 10 milliseconds. So, I'm going with delay of 100.

We'll need a function to manage the timer data (timerUpdate()) - add to milliseconds with each timer loop, then check if we need to add anything else, for example, if we have 60 seconds - seconds should be set back to 0 and minutes increase by 1.

Then we need to add each button's functionality.

Here is the full code:

import flash.utils.Timer;
import fl.data.DataProvider;

bt_lap.enabled = false;
bt_stop.enabled = false;
bt_reset.enabled = false;
bt_continue.enabled = false;

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

var historyArray:Array = [];

updateTime();

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()));
txt_time.appendText(":");
txt_time.appendText((t_msecs>9)?(t_msecs.toString()):(t_msecs.toString()+"0"));
}

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

function timerUpdate(TimerEvent):void
{
t_msecs++;
if (t_msecs == 10)
{
t_msecs = 0;
t_secs++;
}
if (t_secs == 60)
{
t_secs = 0;
t_mins++;
}
if (t_mins == 60)
{
t_mins = 0;
t_hrs++;
}
updateTime();
}

bt_start.addEventListener(MouseEvent.CLICK, startWatch);

function startWatch(MouseEvent):void
{
mainTimer.start();
bt_start.enabled = false;
bt_lap.enabled = true;
bt_stop.enabled = true;
}

bt_stop.addEventListener(MouseEvent.CLICK, stopWatch);

function stopWatch(MouseEvent):void
{
mainTimer.stop();
bt_lap.enabled = false;
bt_stop.enabled = false;
bt_reset.enabled = true;
bt_continue.enabled = true;
}

bt_lap.addEventListener(MouseEvent.CLICK, lapWatch);

function lapWatch(MouseEvent):void
{
historyArray.unshift(txt_time.text);
list_history.dataProvider = new DataProvider(historyArray);
}

bt_reset.addEventListener(MouseEvent.CLICK, resetWatch);

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

bt_start.enabled = true;
bt_lap.enabled = false;
bt_stop.enabled = false;
bt_reset.enabled = false;
bt_continue.enabled = false;

historyArray = [];
list_history.dataProvider = new DataProvider(historyArray);

updateTime();
}

bt_continue.addEventListener(MouseEvent.CLICK, continueWatch);

function continueWatch(MouseEvent):void
{
mainTimer.start();
bt_start.enabled = false;
bt_lap.enabled = true;
bt_stop.enabled = true;
bt_reset.enabled = false;
bt_continue.enabled = false;
}

Thanks for reading!

15 comments:

Anonymous said...

any chance of uploading the FLA file? I think I've done everything you say, but it doesn't display the time...

Kirill Poletaev said...

Are there any errors coming out in the output window? Did you embed your fonts? You might need to embed your font for your textfield to display anything.

Here, I tried uploading the source:

http://www.mediafire.com/?8tfh8p46oh15emk

Anonymous said...

I deleted out the text field and recreated it and this time it worked. Strange.
Thanks for the tutorial. It was exactly what I'd been looking for!

Romuhica said...

Hi Kirill ! I don't know if you'll read this comment, but thanks for this tutorial. I'm practice as3 until 2 years, and I see that I have already very many things to learn. And I can learn thanks to this kind of tutorial. Thanks and happy new year 2011 ! ^^

Anonymous said...

Nice and clean, not only useful educational too!

Thanks
Jay

Anonymous said...

Hi! thankyou , it is very useful; I am a newbie with AS3 and I can't understand what this piece of code means:

txt_time.text = "";
txt_time.appendText((t_hrs>9)?(t_hrs.toString()):("0"+t_hrs.toString()));
txt_time.appendText(":");

What effectively does this lines? and what the symbol "?" and ":" change?
thank you if you answer!

LJK

Kirill Poletaev said...

This line:

(t_hrs>9)?(t_hrs.toString()):("0"+t_hrs.toString())

Is basically an if(){} conditional.

The syntax is this:

(condition)?(value_if_true):(value_if_false);

So that line basically means:

if(t_hrs>9){
txt_time.appendText(t_hrs.toString())
}else{
txt_time.appendText("0"+t_hrs.toString())
}

Anonymous said...

hey buddy my flex can't recognize any component .
the same thing goes with import fl.data.DataProvider;
any help

Sten Lodenstijn said...

Could you please reupload the FLA? Would very appreciate it!

Sten Lodenstijn said...

Nvm, I fixed it! Thanks for tutorial man

OnceUponATimer said...

Great tutorial! One question about text alignment - I'm trying to implement a version of this - but unlike your project, my text realigns itself based on the number. The result is the timer keeps sliding around based on what numbers are in it. Yours doesn't do this, why is that?

onceUponATimer said...

Please ignore the text formatting question - I figured it out!

Ari said...

Kirill, im getting an error message with the DataProvider stating it cannot be found.

HELP

Kirill Poletaev said...

The class can't be found? Did you remember to import it?

Lester Gonzaga said...

hello guys im new to AS3 and i have this problem

fl.data:DataProvider could not be found

anyone who can help me with this? sorry im really a beginner , anyway much appreciated for the help., thanks guys

Post a Comment