Tutorial – Creating a Timer in ActionScript 3

April 10th, 2008 | 41 Comments

Today's tutorial comes with a bit of good news. Yesterday, my pregnant wife and I went to the doctor and discovered that our first baby is a girl! So naturally, I thought I might post a tutorial on how to create a countdown timer with Flash CS3 and ActionScript 3. Since my wife's due date is August 30th, I'll use that as our countdown date.

This tutorial will cover the basics of using the Date() class and the Timer() class in ActionScript 3. The Timer class, as you may know, is new to AS3. The ActionScript 2 equivalent of a Timer object would be the setInterval method, which is no longer available to us in AS3. So, with no further ado, let's get started.

1. Create Your Text Fields. The first thing we need is a dynamic text field that will display the time remaining in days, hours, minutes, and seconds. (For the purposes of this tutorial, we'll be counting down to midnight of our due date.) I'm also going to add a few static text fields to serve as labels, like so:

Text Fields

Notice that I've entered in a bunch of zeros for the dynamic text field. Right now, this text is simply serving as a placeholder. This will eventually be replaced using ActionScript. Also notice that I've aligned the text field to the right. If you align the text field to the left, then when the days remaining reach double (and eventually single) digits, all of the numbers will shift to the left. However, with the text field aligned to the right, the numbers will always remain in the same place as the countdown proceeds.

Also, be sure to give your dynamic text field an instance name. With my dynamic text field selected, I've given mine an instance name of time_txt.

2. Embed the font characters in your Flash file. With your dynamic text field selected, click on the "Embed" button in the Properties Inspector and choose "Numerals" and "Punctuation," as seen below.

Embed Your Characters

If you don't embed all the possible characters that your text field might end up displaying, then the text that is displayed on your users' screens might end up looking weird if they don't have your chosen font available on their system. Since we're only going to be displaying numbers and the colon symbol, we only need to choose "Numerals" and "Punctuation." You can choose multiple items on this list by holding down the Cmd key on the Mac or the Ctrl key on the PC.

3. Create your Date() object in ActionScript. Create a new layer and rename it "Actions." With the first frame of this Actions layer selected hit Opt+F9 (or just F9 on PC) to open up your Actions Panel. Enter the following code:

code

Below the code you'll see the output window that pops up as a result of the "trace" statement on line 3.

I've included line 1 as a commented line of code so you could see that there is more than one way of entering in your dates when you create a new Date object. To explore more ways of entering your date, hit F1 with Flash open and do a search for "Date.Date()".

In line 2, we create a variable called endDate, in which we're storing a new Date object for August 30, 2008. Notice that I've typed "7" for the month, even though August is the 8th month of the year. This is because months start with zero in Flash. So January is 0, February is 1, etc.

In line 3, we've temporarily inserted a trace() statement, with which we're displaying the contents of our endDate variable in the Output window. This is simply for testing purposes, and now that we see it's working, we can delete line 3 (along with line 1, if you wish).

4. Create your Timer object. In order to create a countdown timer that includes seconds, we need to create some functionality that will automatically update our countdown text field once every second. We could create the functionality with an ENTER_FRAME event, but that would cause our code to run over and over again at our current frame rate. Since our file is set to the default frame rate of 12 frames per second, an ENTER_FRAME event would cause our code to try and update our text field 12 times per second, and it really doesn't make sense to force our code to run that often, when the text is only going to change once every second. Using the Timer class, we can specify how often we want our code to run. Add the following code to your Actions layer.

code

On line 3, we create our Timer object and store it in a variable called countdownTimer. When you create a new Timer instance, it expects you to send a number to the constructor. On line 3, we sent the number 1000. This number, which is in milliseconds, represents how often we want the timer to go off. Since we want the timer triggered every second, we need to set it to 1000 milliseconds.

On line 4, we add an event listener to our timer object. The event we're listening for is part of the TimerEvent class, and it's simply called TIMER. This is the event that will be triggered every 1000 milliseconds, and every time it's triggered, it will call on the updateTime function, which we will create starting on line 7.

For now, inside the updateTime function, all we're doing is creating a new date object and then tracing it to the output window. When you create a new Date object without putting anything in the parentheses--as you can see in line 9--the current time is stored in that date object. So you'll notice that when you test your movie (Ctr+Enter on PC, Cmd+Enter on Mac), a new message will pop up in your output window once every second, showing you the current time.

5. Calculate the time remaining. Obviously, with our code as is, we're not quite there. What we need to do now is to compare the current date and time, which is calculated on line 9, with our target date, which is stored in the endDate variable. This calculation is actually much easier than you might think. All you have to do is subtract the current time from the target time, like so:

code

On line 10, we've created a new variable called timeLeft, and in this variable, we've stored the result of a simple calculation. The getTime() method of the date class returns a number that represents the number of milliseconds that have elapsed since midnight of January 1, 1970. Because of the way this works, it's very easy to compare two separate dates and times in order to calculate the time in between them. The numbers shown in the output window above represent the time remaining (in milliseconds) between now and August 30, 2008.

6. Convert from milliseconds to days, hours, minutes, and seconds. For this one, it will be easiest just to show you code and then try to explain it.

code

As you can see, we've got a lot going on now inside the updateTime function. In lines 11-14, we're starting off by calculating the number of days, hours, minutes, and seconds left. But keep in mind that these are not the numbers we want to display. For example, the minutes calculation is showing us the total amount of minutes left between now and midnight of August 30. However, we don't want to display all of those minutes. Rather, we want to display the number of minutes left in the current hour.

So let's say, for the sake of simplicity, that we were two-and-a-half hours away from our target time. In total time, that would be 150 minutes; but we don't want to display this number. Ideally, we'd like to display something that looks like this:

00:02:30:00

This represents days:hours:minutes:seconds. Instead of displaying 150 minutes, we want the number 30 to represent the minutes. Well, we can easily calculate this number by dividing our total minutes by 60 and then taking the remainder. The remainder is the actual number we want to display. Well, in ActionScript, if we want to simply store the remainder of a division problem, we simply use the % sign instead of a forward slash. In this case we would type:

minutes = minutes % 60;

This is assuming, of course, that the value stored in minutes before the calculation was performed was the total number of minutes between now and the target time. And then, when we divide those total minutes by 60, the remainder we get is stored in the minutes variable, replacing the old value, which we no longer need. The above calculation can also be typed shorthand as:

minutes %= 60;

Keep in mind that it's very important to calculate the total seconds, minutes, hours, and days before calculating any of these remainders. Otherwise, our ending calculations would be erroneous.

Once we calculate all our remainders, we're going to convert these numbers into strings in lines 20-23. These strings are stored in new variables. The reason for this is that we're eventually going to end up stringing all of these numbers together for our display, and we want the hours, minutes, and seconds to always display 2 characters. In other words, if the display is showing 9 seconds left in the current minute, we want it to say "09" instead of just "9." So, in lines 25 - 35, we're checking to see if there are 2 characters for each of these numbers, and if there aren't, we're simply adding a "0" in front of the corresponding one-digit number.

You might notice that in the above code, I haven't forced the remaining days to show up with two characters, but if you want to, I'm certainly not going to stop you.

Once all of the numbers are converted to two-digit numbers, we create a new variable in line 37 called time, and in this variable, we're simply stringing all of our values together with a colon in between each of these values. After this is done, we apply the value of this time variable to our dynamic text field so that our users can see how much time is left between now and the time my baby girl is born.

7. Erase the starting contents of the dynamic text field. If you test the movie as is, you'll notice that for one second, we're still seeing "000:00:00:00" displayed in the text field until the first timer event is triggered. This is a little messy, and we don't want our users to see that, so before you publish your finished file, be sure to double-click inside your dynamic text field and remove this placeholder text.

Here's what your finished file will look like:

Here is the source file for your reference: countdown.zip

Tags: , , , ,

41 Responses

  1. Carlos says:

    Hey m8,

    Great news!!! I wish you and your new family all the luck in this new challenge.

    All the best!!!

  2. [...] Read Tutorial and download support files No Comments Leave a Commenttrackback addressThere was an error with your comment, please try again. name (required)email (will not be published) (required)url [...]

  3. [...] my first actionscript app, even thought is a very simple count down timer I got this tutorial from School of flash. I have not checked out any of the other tutorials yet but I am sure they are [...]

  4. Great and very timely tutorial (no pun intended)

    I’m going crazy here, though, and it seems to be on something pretty basic. I’m fishing in hope someone will be able to help me.

    I’m using this tutorial as a base to make a timecode display for an flv, but I can’t seem to make the text appear. I’m pretty new at AS3 and the dynamic text handling is not the same as before.

    So, here goes:

    On my stage, I have an FLVPlayback (cfp) and a dynamic text (tcd) with enough room to display what it has to. Both are named on my on my stage.

    I am tracing the evolution of the time code and it works, so that tells me it doesn’t have to do with the process itself, but with the dynamic text.

    Here’s the portion of the code relevant to this. What am I missing?

    Thanks for any help I can get.
    —————-
    import fl.video.MetadataEvent;
    import fl.video.CuePointType;
    import fl.video.VideoState;
    import fl.video.VideoPlayer;
    import fl.video.VideoEvent;
    import fl.controls.List;
    import fl.data.DataProvider;
    import fl.controls.TextArea;

    ///
    /* Following elements already on Stage, no need to define. For reference & coding hints only.*/
    ///
    //var cfp:FLVPlayback;
    //var cli:List; // list with navigation cuePoints.
    //var tcd:TextArea; // timecode display -> dynamic text

    ///
    // time code…
    ///
    cfp.playheadUpdateInterval = 25;
    tcd.text = Math.round(cfp.playheadTime).toString();//nothing appears
    cfp.addEventListener(“playheadUpdate”, timeCode);
    cfp.play();

    function timeCode(tObj:Object):void{
    var rounded = Math.round(tObj.playheadTime);
    var minutes = Math.floor(rounded/60);
    var seconds = rounded % 60;
    var timecode = (minutes < 10 ? “0″:”") + minutes + “:” + (seconds < 10 ? “0″:”") + seconds
    trace (timecode); // this works: the time code shows in the output panel
    tcd.text = timecode; //does not work.
    }

  5. Nik Rowell says:

    Congrats Craig!…
    Oh yeah – and thanks for the helpful tutorial ;)

  6. Jerry says:

    Thanks for your work

  7. Webomatica says:

    Awesome, I was just looking for how to convert milliseconds in this manner. Thanks!

  8. [...] Source file: countdown.fla Source: Craig Campbell’s Tutorial:Creating a Timer in ActionScript 3 [...]

  9. Wave says:

    I’m getting something weird with the days …
    if i make the timer to be in 2 hours ..
    the days are showing 30 ..
    or if i make it to be in 2 days …
    the days are showing 32 …

    i thought i wrote it wrong but even you fla file is doing the same …
    i’m very new to AS .. even more with AS3 ..

    can you help me ? thank you .
    great tutorial by the way .. i like the way you explain ..

  10. robb says:

    great script! one question I have is how do I get the timer to stop at the specified zero time? or can I have a function that will send it to a different frame?

    thanks in advance

  11. Alin Danila says:

    nice tutorial .. would be even better if you would implement timezone difference to it.

  12. Chepi says:

    Thank you dude! This tutorial saved my behind BIG TIME!

    All the love from South America’s hottest spot…

  13. nihad says:

    Since I did not see a response to ‘Jean-Sébastien Dussault’ with the playheadTime showing up in trace but not showing up in the dynamic text. Simply ensure your dynamic text font in NOT embedded.

    I hope this helps someone.

    Thanks

  14. Anthony says:

    Great tutorial!! But, how can I get it to read the time from a serve so that I can use it on my website??

    Cheers

    Anthony

  15. Matt says:

    I am searching for a short timer that will count down from 5 minutes to zero. Any suggestions. I am completely new to Action Script. I have CS3 so I would like help in AS3 if possible. Thanks. Matt

  16. MIssy says:

    wave you have to put the month one digit back…

    so if you want october you put 9 not 10.
    see the paragraph in the writeup (part 6) about this.

    not sure why the programmer/developer didn’t code it so it did months 1 through 12 like NORMAL PEOPLE read it and not like Flash month array functionality which starts at zero for January to 11 for December…

  17. MIssy says:

    sorry, scratch that part 3 about date()

  18. MIssy says:

    sorry, read part 3 about date()

    you can do a quick fix by setting up some variables to hold the month, date, year and then do a quick math subtract to offset the month so you don’t remember the date() function reads months differently.

  19. Martin says:

    Hi there, great tutorial for a complete noob. Just to pick up on what anthony asked.
    How would you actionscript to get the date from the server? I know it involves the use of something like PHP.
    I’m stuck on how you would code it.
    Sorry for being dumb.

    Thanks

  20. PG Eriksson says:

    Hi,
    How do I get the countdown timer not only go to a speciffic date but to a speciffic time on that day?
    PG

  21. Jax says:

    Great script for of all … but it calculates 30 days wrong when I try it …. hmmm :-)

  22. Terry says:

    How would you get the timer to start at 0 and count forward using sec/min/hrs/days?

  23. Dudeman says:

    Great article. I had a timer in AS2, but never got around to converting it to AS3. This has helped a lot!

  24. david johnston says:

    I would love to see this article, but the pictures of the code and flash shots are not displaying?

    why? can u let me know where I can view them

    dave

  25. Stephen says:

    Thanks alot for the easy to use doc.

  26. Thanks! Useful tutorial!
    Wish your baby girl great health and stay cute!
    Cheers!

  27. Bobby says:

    Thanks man, perfect!!!

  28. myles says:

    The counter works amazing!
    How do I get it to stop at 0 though? So say everything runs down and hits zero and then it stays there. No negative numbers.

    Thanks much

  29. Robert says:

    I have the same question as someone above. Why is it that it displays funny EVEN when I run the file provided for downlaod? it has minus sings in front of my numbers and what not??? time zone maybe? thanks

    this is what that person wrote
    # Wave Says:
    June 3rd, 2008 at 11:32 am

    I’m getting something weird with the days …
    if i make the timer to be in 2 hours ..
    the days are showing 30 ..
    or if i make it to be in 2 days …
    the days are showing 32 …

    i thought i wrote it wrong but even you fla file is doing the same …
    i’m very new to AS .. even more with AS3 ..

    can you help me ? thank you .
    great tutorial by the way .. i like the way you explain ..

  30. Tony says:

    The code above is GREAT! However, I’d like to change it up so I’m counting down ONLY in MINUTES. Also, is there a way to space out the counter? The numbers seem VERY close together.

    Thanks!

  31. Brother says:

    I have a weird problem. I’ve gone through every countdown tutorial I’ve found and I see no difference in my code… The timer runs fine usually for about 6 hours and then suddenly it starts counting hours as fast as second and after a while minutes too pass as fast as seconds.

    I’m getting desperate with this problem, so if anyone can even guess what might be the problem I’d be most thankful.

  32. Wei says:

    It works nicely. I love your tutorial.
    Thank a lot.

  33. Flash Clocks says:

    Thank you for your work creating this tutorial to learn how to create a flash countdown clock in adobe flash program, i believe your actionscript code is accurate or correct to actually make the countdown flash clock work, however i did not test it, i would have out of courtesy but i do not need, i too have a website about flash clocks and countdown clocks, so i created hundreds of each one, i must only say good work.

  34. David says:

    Hi I’m just wondering what changes can be made so that when the countdown finishes it plays an animation or movie clip?

    Thanks
    David

  35. nayon says:

    Thanks Craig for this tutorial……..as i didn’t know where to start how to start for a countdown in flash and your this effort(tutorial)has really helped me from the beginning to the end,and i finally made it.And I m feeling good.Thanks alot!!!I heartedly appreaciate your effort. :)

  36. Jasim says:

    I have some problem could somebody help me or fix it? The flash pro says it’s in line 11 but I don’t see what’s missing? I’m a newbie at this so please.

    var enddate:Date = new Date(2008,7,30)

    var countdowntimer:Timer = new Timer(100);
    countdowntimer.addEventListener(TimerEvent.TIMER, updatetime);
    countdowntimer.start();

    function updatetime(e:TimerEvent):void
    {
    var now:Date = new Date();
    var timeleft:Number = enddate.getTime() – now.gettime();
    var seconds:Number = Math.floor(timeLeft / 1000);
    var minutes:Number = Math.floor(seconds / 60);
    var hours:Number = Math.floor(minutes / 60);
    var days:Number = Math.floor(hours / 24);

    seconds %= 60;
    minutes %= 60;
    hours %= 24;

    var sec:String = seconds.toString();
    var min:String = minutes.toString();
    var hrs:String = hours.toString();
    var d:String = days.toString();

    if (sec.length < 2) {
    sec = "0" + sec;
    }

    if (min.length < 2) {
    min = "0" + min;
    }

    if (hrs.length < 2) {
    hrs = "0" + hrs;
    }

    var time:String = d + ":" + hrs + ":" + min + ":" + sec;

    time_txt.text = time;
    }

  37. [...] – TIMER // RESOURCE1 (schoolofflash.com)::  RESOURCE2 [...]

Leave a Reply