Flash simple timer/countdown

Emanuele Feronato Flash

Sometimes you need a timer or a countdown… for a page, in a game or whatsoever.

So I am going to show you how to create a timer or a countdown. Or both.

And, in next tutorials, how to use it in the games we are creating, of course…

Look at this movie:

On the left we have a timer, on the right a countdown.

Let’s see how to do it.

First, I created two dynamic text items, the one on the left instanced as count and the one on the right instanced as count_down.

Then, in the first frame there is this simple actionscript:

Line 1: Initialize the variable start_time with the current time value

Line 2: Initialize the variable countdown with the amount of milliseconds I want to start the countdown. In this case, since an hour has 3600 seconds or 3600000 milliseconds, the countdown will start from 2 hours

Line 3: Function to be executed at every frame

Line 4: Calculate the difference between the actual time and the start_time value. This is actually the elapsed time.

Lines 5-6: count and count_down text values are updated with the result of a the function time_to_string (a function I created). count will be the elapsed time, while count_down will be the difference from the countdown variable and the elapsed time. Please note that every time explained here is intended to be in milliseconds.

Let’s examine the main function:

Line 9: Calculate elapsed hours dividing the time to convert (function’s argument) by 3600000, the number of milliseconds in an hour

Line 10: Calculate remaining time without the elapsed hours

Lines 11-12: Some thing with the minutes, dividing the remaining time by 60000, the number of milliseconds in a minute

In the same way I calculate the seconds and the 1/100 of seconds. Lines from 16 to 35 just format the string showing the time.

This is a very simple function we will use in the games we are going to create, such as “line rider“.

Download the source code and give me feedback.

Want to learn more? Learn by example!

Get the full commented source code of an actual commercial cross platform HTML5 game!!

Comments 109

  1. bigbill

    Great Timers, quite handy however i’ve tried to put the following code into and can’t get it to work.It just keeps on counting down. Can anyone help please?

    if (_root.count_down

  2. Richard

    Hi. Im Making a linerider game. its basicly finished. ive made it so that you can draw a line, the ball bounces perfectly off it. but i still dont get something. when you’ve finished drawing:

    onMouseUp = function () {
    imdrawing = false;
    };

    that code doesnt want to work :S any tips

    Richard

    PS: this code is RIGHT at the end of the code. is that right or should it be elseware

  3. Pingback: Flash game creation tutorial - part 5.3 at Emanuele Feronato

  4. danny o'dwyer

    im in the same situation as big bill.

    how can you set a limit, so it terminated when it hits a certain time, i cant get it to work.

  5. tom

    to those who were having problems with going to another frame after the timer hits zero, try adding this…

    if (_root.countdown-elapsed_time

  6. pocoster

    ive been puzzled about it going to another frame after zero too ive tried many different ways of doing it and none hav worked anyone got a solution please?

  7. Neo

    Is there an easy way to have the counter start at a certain time. Example: 06:44:33

    6 hours, 44 minutes, 33 seconds

    Thanks

  8. Anavrin

    if(hours == 0 && minutes == 0 && seconds == 0) {
    delete this.onEnterFrame;
    gotoAndPlay(2);
    }
    \\ stops the countdown at 0
    \\goes to frame 2

    setting line 2 to:
    countdown = 24273000 ;
    would start the countdown clock at 6 hours 44 minutes 33 seconds

  9. nor

    hey i just wonder why the code that u give is different from the downloaded file. The code that u give is not working but then the downloaded file is working fine.

    thanx 4 the codes. It’s useful. =)

    have a nice day!

  10. CF

    This is really great. I am a newbie and can’t customize the code for what I would like to accomplish: a simple seconds countdown from 10 to 0 seconds. The countdown should stop at 0. Any easy way to accomplsih this without a lot of code (head spinning);-)

    Thanks!

  11. Jfulton

    i was wondering how you could get the color of the numbers to change color as you get closer to zero. Almost as if your time was running out.

  12. kMan

    A simple solution to stop the ticker would be:

    if (_root.count_down.text == “00:00″){
    gotoAndStop(2);
    }

    And if you want the ticker to stop when reaching all zeros just put a static text containing zeros in frame 2.

    Note: if (_root.count_down.text == “00:00″){
    the zeros must be equal to what you want to display, my example is based on minutes and seconds showing in the count down.

    Hope this will help…

  13. uncle gilbo

    so if i wanted to make a countdown that started @ 2 min would i clear out the elasped hours code and replace the 60000 seconds with 120 and the 6000 min with 2 min?…code is all new to me…sorry if this seems dumb…

  14. Amanda

    I’m having problems with script for stopping the countdown as well.

    I’m using this script for a 2 digit timer with only seconds:

    if (_root.count_down.text=”00″) {
    gotoAndPlay(3);
    }

    With this code in place, my movie entirely skips the countdown, and instead immediately jumps to frame 3. Any advice?

  15. Cristian

    you must place the code like this ……..

    //The Code…..firs Frame….

    function time_to_string(time_to_convert)
    {
    elapsed_hours = Math.floor(time_to_convert / 3600000);
    remaining = time_to_convert – elapsed_hours * 3600000;
    elapsed_minutes = Math.floor(remaining / 60000);
    remaining = remaining – elapsed_minutes * 60000;
    elapsed_seconds = Math.floor(remaining / 1000);
    remaining = remaining – elapsed_seconds * 1000;
    elapsedH = Math.floor(remaining / 10);
    if (elapsed_hours

  16. Cristian

    //in firs frame search for —>>on EnterFrame and replace the code with //this..

    onEnterFrame = function ()
    {

    elapsed_time = getTimer() – start_time;

    _root.count.text = time_to_string(elapsed_time);

    _root.count_down.text = time_to_string(_root.countdown – elapsed_time);

    if (_root.count_down.text == “00:00:00:00″) {
    play();
    };

    };
    stop();

  17. xyxo brocka

    i’m not much with codes. i can’t stop the ticker, i already tried all the suggestions here. perhaps the counter author might figure out a way to make the ticker stop at zero and jump to next scene.

    somehow, this code doesn’t work, doesn’t stop the ticker and doesn’t make the flash jump into a new scene. what seems to be the problem here sir?

    if (_root.count_down.text==”00:00″) {
    gotoAndStop(“start”, 1);
    }

  18. Valerij

    Hi!
    Im using this timer for a game, so the point of the game is to move your cursor through a labyrinth without touching the walls and I want to have a timer on this to see how fast people can do that, but then I need to stop it and view their final time (its in another frame) how do I do that, and if possible I would like to restart that timer again when I get to the next level and again when they finish it view they final overall time. I could work like the once on your Race game (round times and a overall time.

  19. juan

    To stop on zero you must enter this code in onEnterFrame = function

    if (elapsed_time >= countdown) {
    gotoAndStop(2);
    };

    thanks for the code!

  20. Owen

    I’m trying to incorporate this into a game where you go to the “game over” frame after a hitTest. How do I get the timer to freeze when you go to the next frame, so people can see their finishing time?

  21. matt

    i need help… how can i make it so that on a certain time something happens? here is my code so far
    onClipEvent (enterframe){
    if (timer_txt == “00:00:00:10″){
    _root.object.gotoAndPlay(6){
    }
    }
    why doesnt this work?
    email me at soggyoats@gmail.com

  22. Chris

    For days I added this code:

    in the function time_to_string(time_to_convert)

    elapsed_days = Math.floor
    time_to_convert/86400000);

    remaining = time_to_convert-(elapsed_days*86400000);

    The wher the if statments begin this was added:

    if (elapsed_days<10) {
    days = “0”+elapsed_days.toString();
    } else {
    days = elapsed_days.toString();
    }

    then the “return” was adjusted to read:

    return days+” Days: “+hours+” Hrs: “+minutes+” Min: “+seconds+” Sec “+hundredths;

    So I have the days but now I want to limit the hous to only 24 instead of the total minutes remaining in say 10 days.
    for example my readout says:
    10 Days: 249 Hrs: so many Min: etc.. Sec:

    any suggestions?
    e-mail me at cslmke2000@yahoo.com

  23. Ter

    Great countdown code. I’ve modified it to work for my purposes and it’s great. The only thing I can’t seem to figure out is how to pause it and restart it from where I’ve left off.

    I’ve created a Pause button that when clicked, grabs the current time displayed in the count_down textbox stores it in a textbox called pausedtime, hides the count_down text box, unhides the pausedtime textbox showing the time when the Pause button was clicked. Works great. The pause button also creates a var and stores the getTimer when the button is clicked.

    This also hides the Pause button and shows a play button in it’s place. In the Play button I have …

    countdown = (roundtime * 60000) + (getTimer() – pause);

    (I forget how I got that formula, but …)

    This works the first time I click play, the count_down display continues from where it left off, so I thought I’d figured it out. But, if you hit pause again, the next time you unpause it’s wrong.

    I’m having trouble getting my head around the getTimer counting up but the count_down is counting down, and what needs to be subtracted from what to get the count_down to start from where it left off.

    I feel like I’ve tried everything, so anyone who’s got an idea of how to get this workin’, I’d be interested in any ideas you have.

    Thanks

  24. Ter

    Oh, and “roundtime” is input by the user in a previous screen and replaces the 7200000 in line 2 of the original script.

  25. Ter

    Obviously no one frequents this page … but, if you ever come across this and want to pause the countdown portion of Emanuele’s script, I’ve put this code into my play button and it seems to work …

    ============================================
    on (release) {
    start_time = getTimer() – elapsed_time + pause_time;
    var go = getTimer();
    pause_time = go – pause;
    countdown = (roundtime * 60000) + pause_time;
    count_down._visible = 1;
    paustime._visible = 0;
    }
    ============================================

    It took alot of guessing and I’m not sure exactly how I ended up with it or exactly why it works, but it does.

    If anyone wants it and can’t make out my method, I have no problem sending you my working version.

  26. eric

    cant make it stop on “0”
    and go nextframe :(
    any of your suggestion worked for me
    i just have seconds
    its a countdown of 5 seconds and i want it to stop on 0
    and go next frame which say GAME OVER :(

  27. Jeremy

    Thankyou very much for your code!

    I noticed that when the count finishes it starts again. So i added this to the end before the “return hours+”:” etc part.

    if (time_elapsed>=7200000) {
    gotoAndStop (2);
    }

    This makes sure that when the count reaches 0 it stops and does not repeat. Obviously you would have to change the gotoAndStop to whichever frame applies to you and the 7200000 changes depending on your certain time and should match the number on line 2 of the code.

    Thanks again,
    Jeremy

  28. John

    hello, Can someone help me please? I want to load an external XML or TXT file and get from the external file a number to countdown = (external file number);

    thank you

  29. Pingback: Understanding AS3 Timer Class : Emanuele Feronato

  30. yogsmca

    Hi i need to setup for 5 min then i need to show Display on the game that “you have lost already in game” after 5min over

  31. alex

    question, when i insert the time in my html and upload both to the web (they are in the same folder)
    i dont see the timer, please advice

  32. Peter

    How do I make more digits. For example, once the Hours reaches 99, does it reset? Is there anyway to do it so if It reaches 99:99:99:99 then there is another digit thingy. IE: It goes to 01:00:00:00:00 when 1 second passes after 99:99:99:99?

    Please respond and help me if you can
    My email is pstarus@gmail.com

  33. Cat

    For those of you looking for a countdown timer for seconds, that will go to another scene after time is up, this worked for me (found on this link: http://groups.google.com/group/macromedia.flash/browse_thread/thread/cbde84211c16ccd7)

    I replaced

    trace(“countdown complete”);

    with

    gotoAndPlay(“Scene 2″, 1);

    ——————————————–

    var countdown_time:Number = 10;
    var counter:Number = countdown_time;

    countdown_txt.autoSize = “right”;

    function countdown() {
    counter–;
    countdown_txt.text = counter;
    if (counter == 0) {
    gotoAndPlay(“Scene 2″, 1);
    clearInterval(intID);
    }

    }

    countdown_txt.text = countdown_time;
    intID = setInterval(countdown,1000);

  34. Jay

    It kinda works for me, I’m using the coutdown only. The problem is, when I start my game, the timer goes about 3 milliseconds then stops. Any help?

  35. Chetan

    Thank you for the wonderful countdown timer! So far so good, but I have one problem that seems to be a common theme amongst the commenters.

    I’ve tried all the suggestions in the comments on how to stop the countdown at 0, but i’m having no luck. If someone could be gracious enough to send me a copy of the complete code modified to stop at 0 that would be great.

    If it helps, I’m currently using the 00:00:00:00 format, and I’m trying to create a simple 10 minute countdown that stops at 0 and resets back to 10 minutes. The resultant flash movie is going to be embedded into a powerpoint slide to be used in a presentation.

    my email address is chetankania [at] gmail [dot] com

    Thank you again!

  36. Kayro

    I need a similar countdown and countup that counts dollars, rather than time, for a fundraising site. Can you help, or direct me to a script source?

  37. mooky

    How to stop at ZERO

    Look my code >>>

    start_time = getTimer();
    countdown = 1200000;
    onEnterFrame = function () {
    elapsed_time = getTimer()-start_time;
    _root.count.text = time_to_string(elapsed_time);
    _root.count_down.text = time_to_string(_root.countdown-elapsed_time);
    };
    function time_to_string(time_to_convert) {
    elapsed_hours = Math.floor(time_to_convert/3600000);
    remaining = time_to_convert-(elapsed_hours*3600000);
    elapsed_minutes = Math.floor(remaining/60000);
    remaining = remaining-(elapsed_minutes*60000);
    elapsed_seconds = Math.floor(remaining/1000);
    remaining = remaining-(elapsed_seconds*1000);
    elapsed_fs = Math.floor(remaining/10);
    if (elapsed_hours<10) {
    hours = "0"+elapsed_hours.toString();
    } else {
    hours = elapsed_hours.toString();
    }
    if (elapsed_minutes<10) {
    minutes = "0"+elapsed_minutes.toString();
    } else {
    minutes = elapsed_minutes.toString();
    }
    if (elapsed_seconds<10) {
    seconds = "0"+elapsed_seconds.toString();
    } else {
    seconds = elapsed_seconds.toString();
    }
    if (elapsed_fs<10) {
    hundredths = "0"+elapsed_fs.toString();
    } else {
    hundredths = elapsed_fs.toString();
    }
    return hours+":"+minutes+":"+seconds+":"+hundredths;
    }

    Thanks for your help

  38. Pingback: FLASH – Contagem regressiva | Marcus Monteiro

  39. Joel

    Nice script! Does any one know how to make the left counter (elapsed time) stop at a certain time? I really only need seconds and milliseconds (e.g. 03:43). Thanks!

  40. James

    Hi there,

    trying to figure out how to get the pause button/function to work. tried to use the code above posted by Ter but no luck. any suggestions?

  41. Pingback: 15 Countdown Timer | Code&Design-Studio

  42. Aguila

    I’m more interested in the timer, than the count down. Can this be modified to show dollar amounts? Increase $1 every millisecond?

  43. Kyle

    Hi,

    Thanks for providing all this information. Very generous of you..I also tried to create the countdown following your instructions but unfortunately I just failed. I have little flash knowledge and it seems that it is just too complicated for me. I ended up using another countdown that I found on this page:http://www.flashxml.net/countdown.html thanks to the support guys who helped me to make it work out.

  44. Pingback: Understanding AS3 Timer Class « Gabriel's World

  45. Christoph

    Kyle
    on June 8, 2011 at 2:55 pm
    Hi,

    Thanks for providing all this information. Very generous of you..I also tried to create the countdown following your instructions but unfortunately I just failed. I have little flash knowledge and it seems that it is just too complicated for me. I ended up using another countdown that I found on this page:http://www.flashxml.net/countdown.html thanks to the support guys who helped me to make it work out.

    Thanks Kyle for sharing the link to the countdown timer. I found it to be very usefull. Like you i found it very difficult to create my own.

    Cheers,
    Christopher

  46. Tom

    Can somebody please tell me how to stop the timer with the current time still being displayed. eg. When two objects make contact, the timer will stop and show how long they lasted for before they collided.

  47. Pingback: [Download] Flash - Contador regressivo com action script - Marcus Monteiro

  48. Karthik

    Hello,

    I am working on Actionscript 2.0, placing the timer on a frame and the source file dosnt work on it. Do i need to change anything? Please help..

  49. 3man7

    Hi,
    Very useful tutorial! Keep up the good work :D

    @Tom
    Put this code into the frame you want the timer to stop:

    onEnterFrame = function () {
    clearInterval(start_time);
    delete start_time;
    };

    Best wishes,
    3man7

  50. emmy

    hi , pls can any one help me. i needed a countdown timer for internet users on my hotspot. am using a mikrotik os for my hotspot .
    emmy

  51. James

    I have tried everything to get this timer to work, I’m new to actionscript so I’m probably sounding a bit thick. When I open the file up in CS6 and try to play it the timer is going haywire on the last digits, the other digits don’t do anything. I have used other flash programs, but new to cs6. Where am I going wrong. What I would like to use the timer for is counting down on mp3’s so the time would be around 4 to 5 minutes long. this is one timer I would like to use.
    I have looked at the actionscript, but nothing seems to appear different. I would appreciate any help. just tell me where I’m going wrong. I have dowloaded the sourcecode and loaded up the file. the timer appears on the page. I have run it, but nothing!

  52. grungejo

    hie there
    i have a timer on my simple game i tried and when it finish it will go to diffrent page and i have a retry button there , but when i retry everything works except timer and character speed has been increased. As many time i press retry speed increases more and more.
    If any one have solution that will be very helpful. thax

  53. Ale

    Hi there,

    The countdown is perfect but I just need an extra small fucntion. I want to create a button pause and play for the timer.
    I need this button to pause the timer and if you click again keep counting from the time it stopped. When the timer get to 0 I go to frame 2.
    So the timer works perfectly and I go to frame 2 with no problem the only thing is the pause/play.

    Can one of you guys please help me with this?

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *