Simple Flash Countdowns And Timers

July 27th, 2009

I get asked for help doing different variations of Countdowns and Timers all the time, hopefully this post will shed some light on things.

I’ll try cover and explain the four variations I get asked about the most but between them you should be able to create any of the other variations with ease.

1) Simple Countdown In Seconds

1
2
3
4
5
6
7
8
9
var countDownTime:Number = 10;
var startTimeUTC:Number = new Date().getTime() / 1000;
addEventListener(Event.ENTER_FRAME, updateTimer);
function updateTimer (e:Event) :void
{
    var secondsUTC:Number = new Date().getTime() / 1000;
    var timeRemaining:Number =
        ((startTimeUTC + countDownTime) - secondsUTC);
}

Pretty simple code, all we are doing is setting a start time and comparing the current time to it when the update function runs.
Note: The above snippet doesn’t actually do anything with the counter or perform any task when the counter reaches zero. I’m rather just showing how to calculate time, implementation of the code is up to you!

Here is a sample output:

Get Adobe Flash player

Lets take a closer look at the code now.

Line 2 defines startTimeUTC, which is populated by creating a new Date() object.
Note: The Date() object defaults to the current date and time when instantiated without any parameters, so we can immediately call it’s getTime() method and store the result.
We should now have a funny looking number like: 1248677922937, which is actually a UTC representation of the present time in milliseconds. On this occasion however, we just need the seconds, so we would divide that number by 1000, (1 second is 1000 milliseconds).
Now every time the update function runs, we simply replicate this action to create a new Date(), and compare it to the Date() we stored in startTimeUTC.

2) Simple Count Up In Seconds

Measuring time expired is really just the above backwards.

1
2
3
4
5
6
7
8
var startTimeUTC:Number = new Date().getTime();
this.addEventListener(Event.ENTER_FRAME, traceOutput);
function traceOutput (e:Event) :void
{
    var newTimeUTC:Number = new Date().getTime();
    var timeExpired:Number =
        (Math.floor(newTimeUTC - startTimeUTC) / 1000);
}

Example:

Get Adobe Flash player

3) Countdown To Date

This variation builds on the first and second countdown examples but brings more to the sandbox to play with, lets jump straight into the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var futureTimeUTC:Number = new Date(2010, 0).getTime();
this.addEventListener(Event.ENTER_FRAME, updateCounter);
function updateCounter (e:Event) :void
{
    var newTimeUTC:Number = new Date().getTime();
    var timeRemainingUTC:Number =
        futureTimeUTC - newTimeUTC;
    var clockSecondsPast:Number =
        Math.floor((timeRemainingUTC / 1000) % 60);
    var clockMinutesPast:Number =
        Math.floor((timeRemainingUTC / 60000) % 60);
    var clockHoursPast:Number =
        Math.floor((timeRemainingUTC / 3600000) % 24);
    var clockDaysPast:Number =
        Math.floor((timeRemainingUTC / 86400000));
}

This time we have manually set the Date() to January 1st, 2010 (The first month is 0, not 1). The time will default to 00:00am since it was not set, but this is what we want, new years!!

Once we have calculated timeRemaining in the update function, we can parse the information we need from it. Remember it is currently a UTC format number, so think of it as the number of milliseconds, with that in mind it isn’t hard to find what we need.
Note: The % operator is modulus, it returns the remainder of a number.

  • Seconds = (UTC Value / 1000 Milliseconds) Mod 60
  • Minutes = (UTC Value / (1000 * 60 Seconds)) Mod 60
  • Hours = (UTC Value / (1000 * 60 * 60 Minutes)) Mod 24
  • Days = (UTC Value / (1000 * 60 * 60 * 24 Hours))

If you didn’t catch it, we are just dividing by the amount of Milliseconds in each. Here is an example:

Get Adobe Flash player

4) Counter From Past Date

The last variation is really just the previous example backwards, for when you need to count forward from a date in the past.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var startTimeUTC:Number =
    new Date(2009, 06, 26).getTime();
this.addEventListener(Event.ENTER_FRAME, updateCounter);
function updateCounter (e:Event) :void
{
    var newTimeUTC:Number = new Date().getTime();
    var timeExpiredUTC:Number =
        newTimeUTC - startTimeUTC;
    var clockSecondsExpired:Number =
        Math.floor((timeExpiredUTC / 1000) % 60);
    var clockMinutesExpired:Number =
        Math.floor((timeExpiredUTC / 60000) % 60);
    var clockHoursExpired:Number =
        Math.floor((timeExpiredUTC / 3600000) % 24);
    var clockDaysExpired:Number =
        Math.floor((timeExpiredUTC / 86400000));
}

And an example to match:

Get Adobe Flash player

Twitter / RazPeel

One Response to “Simple Flash Countdowns And Timers”

  1. Ernesto Ruiz on April 12, 2010 9:49 pm

    Hi I like your thread, i neet set my countdown to UTC but I cant, can you help me please?

    //First we create a date object. Note that we count the months from “0″!
    var endDate:Date = new Date(2010, 3, 18, 17, 0, 0, 0);
    //next we create a timer that will update the time every second
    var timer:Timer = new Timer(1000);
    //we add an event listener to the timer and then we start it
    timer.addEventListener(TimerEvent.TIMER, updateTime);
    timer.start();
    //Calculate the time remaining as it is being updated
    function updateTime(e:TimerEvent):void{
    //we create a variable to hold the current date
    var currentDate:Date = new Date();
    //we calculate the time to FIFA World Cup 2010
    var timeLeft:Number = endDate.getTime() – currentDate.getTime();
    //we convert the remaining time into seconds, minutes, hours, and days
    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;

    //we convert the numbers to strings
    var sec:String = seconds.toString();
    var min:String = minutes.toString();
    var hrs:String = hours.toString();
    var d:String = days.toString();

    //if we have a single digit we add “0″ in front of it
    if (sec.length < 2) {
    sec = "0" + sec;
    }

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

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

    //we create a variable to hold all elements and then we add it to our text field
    var time:String = d + ":" + hrs + ":" + min + ":" + sec;
    time_txt.text = time;
    }

Trackback URI | Comments RSS

Name (required)

Email (required)

Website


Speak Your Mind





Powered by WP Hashcash

About

Name: Raz Peel

Raz Peel 2009

Employer: Sapient
Occupation: Web Developer
Contact: raz@wizardelraz.com