Build a Simple Countdown Timer in Flash

If you’d like to download the files used in this tutorial to practice these techniques, visit www.layersmagazine.com and navigate to the Magazine section. All files are for personal use only.

A common task for Flash developers is to create countdown timers that let users know how long it is until a certain conference or event takes place. You can get very creative with the style of your timers but the ActionScript needed to build them doesn’t change much. In this tutorial, you’ll take some Photoshop artwork and build a simple countdown timer in Flash.

1 OPEN THE PHOTOSHOP FILE
Download the files for this tutorial from www.layersmagazine.com. The ZIP file contains a PSD file named “countdown.psd.” Open this file in Photoshop. This is the artwork that you’ll use as the basis of your countdown timer. The top layer (called chrome) makes up the main visuals for the timer. The bottom layer (called backdrop) contains the background for the numbers that you’ll create in Flash. You’ll import this PSD file directly into Flash.

Flash Tutorial

2 CREATE THE FLASH DOCUMENT
Launch Flash and create a new ActionScript 3.0 document. This tutorial doesn’t use any of the new features found in Flash CS4, so it will work with earlier versions of Flash as well. Since this movie will simply count down every second, we can lower the frame rate quite a bit to lessen the system resources used by the movie. In the Property inspector, change the FPS value to 2. Save this FLA somewhere on your hard drive as countdown.fla.

Flash Tutorial

3 IMPORT THE PSD FILE
Now you’ll import the PSD file into your Flash movie. Select Import to Stage from the File>Import menu. Navigate to the countdown.psd file and click the Import button. This opens the Photoshop Import dialog. Uncheck the Background layer, as you won’t need that in the Flash movie. Shift-click the two remaining layers and change the JPEG compression to 90 by clicking on the Custom radio button. Now click the Set Stage Size to Same Size as Photoshop Canvas checkbox to make Flash crop the movie to the same size as the PSD. Click OK to import the file.

Flash Tutorial

4 ADD SOME LAYERS
After importing the PSD file, you should see the same layer structure in the Timeline panel as you saw in the Layers panel in Photoshop. Rename Layer 1 by double-clicking on it and entering “actions,” then lock it so no visuals can be placed on it. You’ll write all of your ActionScript code on this layer. Now click the New Layer icon, rename it “numbers,” then drag it between the backdrop and the chrome layers. This layer will contain the dynamic text fields for the days, hours, minutes, and seconds that constitute the core of the countdown timer.

Flash Tutorial

5 CREATE A TEXT FIELD
Select the first frame on the numbers layer in the Timeline and get the Text tool (T). Click on the Stage to create a new text field and enter three digits just so you can preview what it will look like. Switch to the Selection tool and click on the text field to select it. In the Property inspector, select Dynamic Text from the Text Type drop-down menu, give it an instance name of “daytxt,” change the font Family to Myriad Pro, Style to Bold Condensed, Size to 20, and make the Color white. Also make the text Format Align Center in the Paragraph section. Position the text field in the Day field on the Stage.

Flash Tutorial

6 EMBED THE FONT
One thing that beginning Flash developers often forget to do is embed the fonts for dynamic text fields. You can’t rely on end users having Myriad Pro on their system so embedding the font assures that everyone will see the same thing. Select the text field and then click on the Character Embedding button in the Property inspector. When embedding fonts you only want to include the characters you’ll need to help keep the file size down, so select Numerals from the list and click OK.

Flash Tutorial

7 CREATE THE REMAINING TEXT FIELDS
Repeat Step 5 and Step 6 for the remaining three text fields. Give the hours text field an instance name of “hrtxt,” the minutes text field an instance name of “mintxt,” and the seconds text field an instance name of “sectxt.” Position all of the text fields in the appropriate places. Tip: The easiest way to insure that all the text fields have the same properties is to simply copy the first one you created, paste it to create duplicates, then change the instance name of each duplicate in the Property inspector. Now it’s on to the code!

Flash Tutorial

8 START THE ACTIONSCRIPT CODE
Select the first frame of the actions layer and open up the Actions panel by pressing Option-F9 (PC: Alt-F9). The first thing you’ll do is create a new Date object that holds the date that you’re counting down to. To the Date object you pass in the year, month, day, and time. One important thing to remember is that Flash starts counting months with 0, so December will actually be passed in as 11, not 12. Add the code shown in the image above into the Actions panel. Here we’re only passing in the hour but you can also input the minutes and seconds.

Flash Tutorial

9 ADD THE ENTERFRAME LOOP
Obviously, you’ll need to constantly update the text fields on the Stage and using an enterframe loop is one way to do that. Essentially, you define a function that gets called every time a new frame is reached. For this example that will happen two times a second since the frame rate (FPS) is set to 2. You could use a Timer object to do this as well. Enter the code shown in the image above into the Actions panel. This creates an enterframe event that calls a function called loop.

Flash Tutorial

10 GET THE CURRENT DATE
The first thing you’ll do in the loop function is find out the current date and time so you can calculate how long it is until your event, and to do this you simply create a new Date object and pass in no parameters. Next, use the getTime method to subtract the current time from the time of the event to get the total time remaining. This value will be the total number of milliseconds until the event and is stored in ms variable.

Flash Tutorial

11 CALCULATE THE VALUES
Now you have the total number of milliseconds until your event but obviously you need to break that into days, hours, minutes, and seconds. Enter the code from the image above into the Actions panel. To get the number of seconds we simply divide the number of milliseconds by 1000. For minutes you divide the number of seconds by 60. (Noticing a predictable pattern here?) We wrap each of these operations in the Math.floor function so that it rounds the numbers down to make them nice and clean.

Flash Tutorial

12 CORRECT THE VALUES
In the previous step you calculated various values needed to display the countdown. But there’s a problem. You can’t display the total number of seconds because it would be a huge number. You need to normalize these values; the way to accomplish this is to use a modulus (%) operator. Input the code shown in the image above. Let’s use seconds for example. In the code shown in the image, we’re taking the seconds and modding them by 60. This will divide the number by 60 and return the remainder—this is the number we want displayed.

Flash Tutorial

13 SET THE TEXT FIELDS
Now that you’ve calculated the values, you can format them to be displayed in the text fields. Enter the code shown in the image above into the Actions panel. For the hours, minutes, and seconds you want to add a leading zero if the number is below 10 to make it look nicer. In this code, you’re testing the values and adding the zero if necessary before outputting the value. We use the toString method on our numbers so that they’re converted to strings before trying to put them into the text field.

Flash Tutorial

14 THE FINISHED TIMER
Now press Command-Return (PC: Ctrl-Enter) to test your movie and see the finished countdown timer. There are many ways in which you can customize it. You could, for instance, also display the milliseconds. For that, increase the frame rate of your movie to make it look right. You can also pass in the target date via Flashvars to make a timer that could be reused for multiple events. Countdown timers are a simple way to help promote your event and, as this tutorial has shown, they’re relatively easy to create in Flash.

Flash Tutorial

ALL IMAGES BY LEE BRIMELOW UNLESS OTHERWISE NOTED

Share & Enjoy


Similar Articles

 

  1. [...] This post was mentioned on Twitter by HowDo.us, Stephanie Moore , ITexpress, Illastr8, apex and others. apex said: build a simple countdown timer in flash http://www.layersmagazine.com/build-a-simple-countdown-timer-in-flash.html [...]

  2. [...] Click here to read the rest of the tutorial Share This [...]

  3. milo (Reply) on Tuesday January 12, 2010

    Thanks for this- I’ve been wanting to try to do this, but lack the as3 skills to get the job done.

  4. Tyson (Reply) on Tuesday January 12, 2010

    Great tut. I have used this countdown for the past month, and our clients love it!

  5. Ric Crawford (Reply) on Tuesday January 12, 2010

    This is brilliant – so effective, yet simple to create! Thank you.

  6. Richard White (Reply) on Tuesday January 12, 2010

    Did this exactly as shown and all I get
    1119: Access of possibly undefined property txt through a reference with static type flash.text:TextField.

  7. saeid (Reply) on Tuesday January 12, 2010

    thanks you soooooooooo much

  8. MOTO (Reply) on Tuesday January 12, 2010

    I have created your countdown timer which works and was easy to create, but I cannot get it to load into my Main swf for some reason.

    For my main webpage SWF, I’m using Actionscript 2.0 and not 3.0.

    1) Does the countdown timer not work with actionscript 2.0?

    2) I also have a stop () actionscript on my main page and is on a different layer than the action I used to put the countdown action. Does the “stop” function stop the timer?

    3) Also, I’ve tried to use a button to eternally load the movie clip on my main SWF; but I can’t get it to load either. I don’t know much about 3.0 but it doesn’t look like you use the behaviors panel to assign action to buttons.

    What are the steps that I need to take to incorporate this on to my main SWF document?

    Thanks!

  9. Shane (Reply) on Tuesday January 12, 2010

    Tried this verbatim with the result of:
    1120: Access of undefined property hrtxt.
    1120: Access of undefined property mintxt.
    1120: Access of undefined property sectxt.

    can someone tell me what this means, as I’m quite new to Adobe and AS3.

    Thanks

  10. Jennifer (Reply) on Tuesday January 12, 2010

    this did work for me, this was great thank you so much. And for some that were having trouble it could be the problem between 2.0 and 3.0 it has to function with 3.0 I do believe. The undefined property though maybe one wrong colon or semi colon something little like that or the instance names such as daytxt hrtxt not matching names in the script or not matching in the properties panel.

  11. kelly Han (Reply) on Tuesday January 12, 2010

    I’ve done the same exact thing it says in the tutorial but i get the message
    “scene 1, Layer ‘actions’, Frame 1, 1071: Syntax error: expected a definition function loop(e:event):void”

    what do I do??

  12. SWiSHZOOM (Reply) on Tuesday January 12, 2010

    wow your tutorials is very cool and easy to understand

    thank you very much mister

  13. Alex (Reply) on Tuesday January 12, 2010

    This is a really nice timer. Could you let us know how to modify it if we wanted to use the time from a server rather than a user’s clock? I’ve found several examples of using PHP to call the sever time, but not sure how you go about modifying the script in the tutorial

    Thanks

  14. adimaryanto (Reply) on Tuesday January 12, 2010

    I use adobe flash CS4 v 10.
    I followed all the instructions … but why always error / does not work when I press ctrl = enter

    This is his code

    var targetDate:Date = new Date(2010, 8, 25, 15);

    addEventListener(Event.ENTER_FRAME, lOOP);

    function loop(e:Event):void
    {
    var nowDate:Date = new Date():
    var ms:Number = targetDate.getTime() – nowDate.getTime();
    var sec:Number = Math.floor(ms/1000);
    var min:Number = Math.floor(sec/60);
    var hr:Number = Math.floor(min/60);
    var dary:Number = Math.floor(hr/24);

    sec = sec % 60;
    min = min % 60;
    hr = hr % 24;
    }

  15. hough (Reply) on Tuesday January 12, 2010

    Alex…
    correct:

    var targetDate:Date = new Date(2010, 8, 25, 15);
    addEventListener(Event.ENTER_FRAME, loop);
    function loop(e:Event):void
    {
    var nowDate:Date = new Date():
    var ms:Number = targetDate.getTime() – nowDate.getTime();
    var sec:Number = Math.floor(ms/1000);
    var min:Number = Math.floor(sec/60);
    var hr:Number = Math.floor(min/60);
    var dary:Number = Math.floor(hr/24);
    sec = sec % 60;
    min = min % 60;
    hr = hr % 24;
    }

  16. [...] Countdown Okay, well I think I’m giving up on any flash tutorials that are complicated code like this, last few haven’t been working, and I’m at my wits end. I think I need to focus on visual stuff instead of use and functionality….grrrr… The tutorial is from Layers Magizine and you can check it out by Clicking Here. [...]

  17. HiRize (Reply) on Tuesday January 12, 2010

    I had problems with this script also, but as a total newb to Flash and any sort of scripting, I carefully checked my typing of the script. Sure enuf, I won the fight, as I kept finding small mistakes – spaces, colons, etc – that kept the script from working. Please don’t give up on us, Lee. This is a great benefit. And besides, those that do get it, get it!
    Thanks for your hard work.

  18. MmE (Reply) on Tuesday January 12, 2010

    Hello!
    How can I modified the code so that the countdown only shows the hours, minutes, seconds, without the days!
    Thank u!

  19. Zoli (Reply) on Tuesday January 12, 2010

    Good working, but this is the good script:

    var targetDate:Date = new Date(2011, 11, 13, 14);

    addEventListener(Event.ENTER_FRAME, loop);

    function loop(e:Event):void
    {
    var nowDate:Date = new Date();
    var ms:Number = targetDate.getTime() – nowDate.getTime();
    var sec:Number = Math.floor(ms/1000);
    var min:Number = Math.floor(sec/60);
    var hr:Number = Math.floor(min/60);
    var day:Number = Math.floor(hr/24);

    sec = sec % 60;
    min = min % 60;
    hr = hr % 24;

    daytxt.text = (day < 100) ? "0"+day.toString() : day.toString();
    hrtxt.text = (hr < 10) ? "0"+hr.toString() : hr.toString();
    mintxt.text = (min < 10) ? "0"+min.toString() : min.toString();
    sectxt.text = (sec < 10) ? "0"+sec.toString() : sec.toString();
    }

  20. Gregir (Reply) on Tuesday January 12, 2010

    Followed this tutorial to the letter, and set the target date to two weeks in the future, but the clock reports there are 36 days left.

  21. Gregir (Reply) on Tuesday January 12, 2010

    My mistake. I didn’t note that date values are zero-based.

  22. David (Reply) on Tuesday January 12, 2010

    Thanks for the script, love it.

    I just have couple of question is there a way to display text when the timer expires? And a simple way to add multiple years so it keeps ticking directly after the target date has passed?

  23. Sarah (Reply) on Tuesday January 12, 2010

    Very informative. Thank you! I especially like the use of screen grabs. It made this tutorial very easy to follow. I’ve bookmarked this website and will definitely be back.

  24. Brian (Reply) on Tuesday January 12, 2010

    I’ve followed this completely and the countdown simply does not work when I test it by pressing Ctr & Enter. Help!



Planet Photoshop Photoshop World Kelby Training Lightroom Killer Tips NAPP Scott Kelby