Tips & Tricks 6: How to Create a Countdown Timer in Actionscript 3.0 July 9, 2009

Tips & Tricks 6: How to Create a Countdown Timer in Actionscript 3.0

by flashuser in ActionScript 3.0, Flash Tips & Tricks

I will show you how to create a simple yet effective countdown timer in ActionScript 3.0. It counts from days to seconds and it’s useful when you schedule anniversaries, appointments, holidays.

1. Create a dynamic TextField and aligned to the right.

2. Give it an instance name, I call it countdown_txt.

3. In the first frame of the scene open the Actions tab and paste this code:

this.addEventListener("enterFrame",startMovie);

function startMovie(e:Event) {

	var today:Date = new Date();
	var curTime = today.getTime();

	var myRetirement:Date = new Date(2050, 7, 9);// 2050 August 9 -- months are from 0 to 11

	var myRetirementTime = myRetirement.getTime();// get the time in miliseconds of myRetirement
	var timeLeft = myRetirementTime-curTime;

	var seconds = Math.floor(timeLeft/1000);
	var minutes = Math.floor(seconds/60);
	var hours = Math.floor(minutes/60);
	var days = Math.floor(hours/24);
	var years = Math.floor(days/365);

	seconds = String(seconds%60);

	if (seconds.length<2) {
		seconds = "0"+seconds;
	}
	minutes = String(minutes%60);

	if (minutes.length<2) {
		minutes = "0"+minutes;
	}
	hours = String(hours%24);

	if (hours.length<2) {
		hours = "0"+hours;
	}
	days = String(days%365);

	if (days.length<2) {
		days = "0"+days;
	}
	years = String(years);

	var count:String = years+":"+days+":"+hours+":"+minutes+":"+seconds;
	countdown_txt.text = count;
}

Example:



Get Adobe Flash player

Subscribe to our RSS Feed and follow us on Twitter

Enjoy this post?

Help us grow this site and share the content with others among you.

img-delicious img-digg img-twitter
img-stumbleupon img-facebook img-mixx

Comments
  1. how can you make it so when it hits 0:00:00 (target date) it displays a message instead of counting up?


  2. All you have to do is test the timeLeft variable. Here is the code for that. Delete the line 41 and 42 and paste this code:

    if(timeLeft <=0)
    {
    countdown_txt.text = "Happy Birthday!!!";
    removeEventListener("enterFrame", startMovie);}
    else{
    var count:String = years+":"+days+":"+hours+":"+minutes+":"+seconds;
    countdown_txt.text = count;
    }


Leave a Comment

Note: You can get a Gravatar account for free so your avatar can be shown when you post a comment on any website that supports gravatars.