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:
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.
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:
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.
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:
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.
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:
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.zipTags: actionscript 3, countdown, Flash, Timer, tutorial