Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done
Look, an author!

Date Countdown Timer

by senocular   | filed under Flash and ActionScript

Here you will learn to create a countdown timer which counts down from the current date and time to a specific date and time in the future. This example will use days, hours, minutes, seconds and even milliseconds retrieved from Flash's Date object to calculate that countdown. But, not only will you learn what is needed to calculate that countdown; you will also learn how to incorporate custom images to represent your numbers in that countdown.

Here is an example of what I am referring to:

[ counting down till Christmas! ]

There are two parts to this tutorial:

  1. First there's making the graphics, which doesn't seem that difficult (though there's some tricks in helping with that.)
  2. Then there's the coding to make it all work, which actually has some tricks of its own as well.

I'll explain the creation of the graphics as they were made in Photoshop and Image Ready before imported in Flash. In Flash is where the Actionscript is added to make the timer to use those graphics in displaying the countdown for your date.

Creating and Importing the Graphics:

The actual making of the graphics is nothing special. All you really need is 10 numbers of 0 through 9 and any kind of character you want to use to separate them in the final countdown (if any). This example uses a period for separation though a colon (:) is quite common. Other desired graphics you would also want to include.

  1. Open up Photoshop (or your image editing program of choice) and make your images. Here you can see the elements I've created in Photoshop for this example:

[ the elements in Photoshop ]

  1. Next, switch over to Imageready and slice up your image into individual elements. You will want to do this division here and not in Flash as it will save you a lot in file size in the long run. Each digit will need to be its own slice and, to make it easier on yourself later, preferably all the same size. The DAYS, HOURS, MINUTES, SECONDS and MILLISECONDS text will also be divided since their positioning will be decided within Flash. The "Horah!" text can be its own single slice since it will be alone in the frame for when the date has been reached:

[ slices in Imageready ]

Before you start exporting from here, however, you should consider naming your slices. This will no only make it easier to determine what is what when dealing with your images, but you can also make importing a little easier on yourself.

Each of the numbers for this countdown will exist in a single movieclip, each in their own frame. That way, to show a number, we just tell a number movieclip to go to and stop at the frame corresponding to that number. Flash, being the crafty program it is, can recognize image file sequences with similar names and import them individually frame by frame as if to create a frame by frame animation of those images directly within the movieclip they were imported to. That's pretty much what we'd be after with the number sequence. So, with that in mind, you will want to give your number slices names that will create image files something along the lines of:

image_0.gifimage_1.gifimage_2.gifimage_3.gifetc...

Clarification The above naming is used so that Flash will see those images as a sequence and import them frame by frame into the movieclip in which they will be imported. The easiest way to accomplish this in ImageReady is to just give the slices of your numbers names which are the number itself.
  1. Open the Rollovers panel showing all your slices and give each number the proper name which is simply their number:

[ naming slices in Rollovers panel ]

  1. Now you can exporting those images. Be sure to set up a custom export settings (Other...) which will let you specify an export name of some prefix + sliceName + .ext so the number slices will get proper names relating to their sequence. If you want, you can select only the slices you've created and only export selected; otherwise other non-essential slices will be exported with everything else. However, since those slices weren't named, they will be easy to weed out when importing the wanted slices into Flash.
  2. With the imagery finished, you can begin importing them into Flash. So fire up Flash and begin importing. All images aside from the numbers 0 - 9 can be imported directly into the library. Those numbers, however, are going to be imported as a sequence in their own movieclip. So make a new movieclip calling it "numbers" and import your 0 image.If all goes well and your images are properly named, you should receive a dialog box stating that this image appears to be "part of a sequence of images." Select "Yes" and all of your images of 0 - 9 should be imported frame by frame into that movieclip as a sequence. Then you should have 10 frames with frame one with 0 image, frame two with 1 image etc., up until frame ten where the image for 9 is:

[ ten frames of numbered images ]

For the most part, all that really remains graphically is setting up the countdown clip itself. This clip will consist of one of these numbers movieclips for each digit it needs to display in the countdown. Then, as Flash calculates the countdown, it will tell each of these numbers movieclips to go to the correct frame representing the number they need to display. To display 0, for example, a numbers movieclip would need to go to and stop at frame one, etc.

Now back to Flash...

  1. Make a new movieclip and call it something like "counter." This movieclip will contain those numbers movieclips for each number in the counter. This example uses 3 digits for days, 2 for each hours, minutes and seconds and another 3 for milliseconds. Add in the numbers movieclips and any other graphics symbols you may need such as the periods separating the numbers.In importing the numbers we used a trick to make it easier for those numbers to be automatically imported frame by frame in Flash making it easier on importing process. This tutorial will continue to use such tricks as making life easier is always, I think, a good thing. That leads us to the big trick of this example which is the process used in identifying each digit in the countdown. What this relies on is the names of each of the numbers movieclips in the counter clip.
  2. In naming the numbers movieclip, you'll need to follow the following format:(time unit variable) + underscore + (character number)For example. The variable which is going to be used to count the days will be called days. For the first numbers movieclip making up days in the countdown, it represents the first character in the days total 3 digits or, in Flash, 0 - relating to charAt(0). So, the name for that movieclip will be days + underscore + 0 or days_0. This trick allows coding to be much easier. You'll see that later on. Here are all the names of the numbers clips in this example:

[ naming for the numbers movieclips ]

  1. Now just throw this counter movieclip in frame 1, add the DAYS, HOURS, MINUTES, SECONDS and MILLISECONDS images to label each part, throw the Hoorah! in frame 2, set your play head back to frame 1 and begin coding!

You have just finished the graphical portion of this tutorial. Before you start rejoicing, we haven't touched the coding aspect of the animation yet. The coding for your countdown timer will begin on the next section.

The idea behind the counter is having two dates in time and finding the difference between them. At first, that may seem difficult because you would have to think that you would need to first find the difference in days, then figure into that the difference in hours and then minutes and so on. The good news is that it's not that difficult and the difference can actually be done directly on the millisecond level meaning only one calculating in difference of milliseconds needed to find the number of milliseconds between two dates. The bad news is that the days, hours, minutes etc. will still need to be figured out from those milliseconds so some tedious work will still be needed.

  1. The first step is defining your event date - or the date in time you'll be counting down to. This is done using the Date object to create a date. Be wary of the month input for your Date definition, however, as the Date object uses month values of 0 to 11 and not 1 to 12 as you may be used to. This example uses Christmas, so Christmas will be used as the date to countdown to. You can use any date you want though. Also, because the comparison between the current date and this event date is done through milliseconds, those milliseconds will need to be retrieved as well using getTime();
// first get this current year so this example

// remains valid for some time to come

currentDate = new Date();

thisYear = currentDate.getFullYear();

eventDate = new Date(thisYear, 11, 25);

eventMillisecs = eventDate.getTime();
  1. Now that the eventDate has been defined, we can start running an enterFrame event to continuously countdown from the current date to that date. Because the current date is always changing, its never now for longer than it is... now, we need to keep calculating the current date (variable currentDate) and its milliseconds from getTime() on each frame so the timer can be updated accordingly. The comparison is a simple subtraction of the currentDate's milliseconds from the eventDate's milliseconds. This will be set to a msecs variable which will also provide the display of the milliseconds on the countdown timer. Since the counter movieclip has all the numbers within it, it's easiest to use it's onEnterFrame event to handle this, and in fact necessary given this approach.
counter.onEnterFrame = function(){

	currentDate = new Date();

	currentMillisecs = currentDate.getTime();



	this.msecs = eventMillisecs - currentMillisecs;
  1. Next we can do a simple check to see if the eventDate has been reached. All this requires is checking to see if the msecs is a negative number. If it is, it would mean the current time is past the event time and therefore the event has been reached. If that is the case, you would want to display the result of the countdown, where here, its playing to the next frame showing the big Horah!
if (this.msecs <= 0){

		play();

		return;

	}
  1. If the date hasn't yet been reached, which will most likely be the case, then you'll need to start calculating and formatting your numbers. This means getting days, hours, minutes and seconds out of your milliseconds and making sure they fit the format of your counter. This counter uses 3 characters or digits for days, 2 for hours, 2 for minutes, 2 for seconds and 3 for milliseconds - each will have to be formatted accordingly. There are 3 steps in this process:
  1. Determine each days, hours, minutes and seconds values out of your milliseconds
  2. Reduce the value of each to not exceed it's expected range, i.e. hours should not go above 24 and minutes not above 60. Days can go higher since that is the highest value and expected to be high.
  3. Convert each value to a string and add leading 0s to make the value reach the number of digits needed to fulfill its requirement. If seconds for example is 5, it needs to become "05".

The first step is easily accomplished with division. You should already know to find out how many seconds are in 3000 milliseconds you just divide by 1000, and to get the minutes from the seconds, divide by 60.

Step number 2 is accomplished using the modulo (%) operator which takes any value and returns the remainder of a division. Take, for instance, 90 seconds. This, when divided by 60 gives you 1 for 1 minute. But there's still 30 seconds remaining. How is that retained? From a mod! If you take that 90 and mod it by 60, you'd get 30 - the remaining number of seconds or the remainder left over from a division.

The last part just means adding 0s in front of the number (as a string) if it's not long enough.

this.secs = Math.floor(this.msecs/1000); // 1000 milliseconds make a second

	this.mins = Math.floor(this.secs/60); // 60 seconds make a minute

	this.hours = Math.floor(this.mins/60); // 60 minutes make a hour

	this.days = Math.floor(this.hours/24); // 24 hours make a second



	this.msecs = string(this.msecs % 1000);

	this.secs = string(this.secs % 60);

	this.mins = string(this.mins % 60);

	this.hours = string(this.hours % 24);

	this.days = string(this.days);



	while (this.msecs.length < 3) this.msecs = "0" + this.msecs;

	if (this.secs.length < 2) this.secs = "0" + this.secs;

	if (this.mins.length < 2) this.mins = "0" + this.mins;

	if (this.hours.length < 2) this.hours = "0" + this.hours;

	while (this.days.length < 3) this.days = "0" + this.days;
  1. Finally, at the end of the counter onEnterFrame function, run through all the movieclips in this counter movieclip (each numbers movieclip) and call the function which dissects the name of each of those clips and tells it to go to the appropriate frame based on the value of the previously defined variable it references.
for(movie in this){

		if (this[movie]._parent == this) this[movie].evaluateFrameFrom(this);

	}

}; // end onEnterFrame

What is this function you ask? It's the evaluateFrameFrom function which is the very last thing that needs to be defined for all this to work, fully implementing the trick that makes what could have been a lot of work... less. This will be made as a MovieClip.prototype so that all movieclips will inherently have access to the function whenever they want - namely, all the numbers movieclips.

  1. So, for this thing to function we need it to dissect the name of each movie as we have so cautiously and carefully preplanned and find out which number value and ultimately which frame each numbers movieclip is to display. The names, if you'll remember, are made up of the variable they use and the character in the variable they represent (a reason for making sure each value had the right number of digits). With that information we can snag the value of the variable as a string (this is the variable as its stored in the counter movieclip - its passed as an argument so that variable can be accessed from it), then use charAt and with the correct character number to find out which number it should show. Add 1 to that number and you have a frame to go to (remember 0 is on frame one, so all frames are offset by 1).
MovieClip.prototype.evaluateFrameFrom = function(variableClip){

	var nameArray = this._name.split("_");

	var numberSet = variableClip[nameArray[0]];

	var character = number(nameArray[1]);

	var frame = 1 + number(numberSet.charAt(character));

	if (this._currentframe != frame) this.gotoAndStop(frame);

};

Just to further enforce what's going on here, let's do a quick example using the day_1 numbers movieclip. In looping through its movieclips, counter will eventually reach days_1 and run evaluateFrameFrom on it passing in itself (counter). days_1 is separated into an array by dividing the name by its "_" character giving "days" (nameArray[0]) and "1" (nameArray[1]). The value of days is then retrieved from the passed variableClip (counter) using associative array syntax and is set to numberset.

The value of days in variableClip would be a string something along the lines of "045". Character is then used to get which of those 3 values this movieclip is to represent. It is just nameArray[1] turned into a number or "1" to 1. So, charAt(1) of "045" would be 4. Turn that into a number and add one and you get frame 5 where the image of the 4 is located. The movieclip, days_1, is then played to that frame to show it.

Though a bit tricky in some senses, you can now have a template for making countdown timers to any date! Should you want to countdown to Christmas, or maybe your birthday or even the release of a new movie, you now know how to make that happen and how to do so with your own custom images to display for numbers - and they technically don't even have to be numbers. Instead you could use 3 cows standing on top of each other to represent 3 or something even more abstract all together. The decision is yours. Have fun with it.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.

Your support keeps this site going! 😇

-senocular

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--