Flash simple timer/countdown

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.

  • Still using AS 1.0 ?

  • 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

  • bigbill

    That should be –
    if(_root.count_down

  • mousey

    Cool, really easy and really fun >!

  • bigbill

    How do you goto another frame when the countdown reaches 0?
    btw Have problems posting.

  • Alex

    nice, i used it in one of my games

  • 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

  • brisa

    Thanks for posting this. I used part of the code to fix my counter and it works perfect.

    Nice work:)

    Brisa

  • abhilash

    nice tutorial

  • Pingback: Flash game creation tutorial - part 5.3 at Emanuele Feronato()

  • lister

    That’s great!

    Is there a simple way to make a start/stop & reset button for this?

  • 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.

  • 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

  • tom

    or instead of using “gotoAndPlay()”, maybe try using “gotoAndStop”.

    seems to work better for me.

    – tom

  • 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?

  • Chandler

    how do I get it to stop on O? I’ve tried everything I can think of but can’t get it working…

  • 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

  • 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

  • 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!

  • cpmartin

    How could this be converted into a Two minute timer? Any help is much appreciated. Thank you in advance.

  • 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!

  • 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.

  • Jfulton

    Also i cant seem to get the timer to stop. Can anyone help me with this?

  • 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…

  • 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…

  • Hi
    Thanks it is working fine.

    Regards
    Sunil kumar

  • 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?

  • 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

  • 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();

  • 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);
    }

  • thanks for this counter. I will put in a website that i have in mind

  • jr

    I want the timer to count down from example 16 min 41 sec, I don´t get how to do it?? Someone know how to do it?

  • jr

    I got it.

  • 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.

  • please guys, i want to stop timer from reading or counting, guys i want you to give me the codes or by sending it to my email box. thanks guys.

  • Also i cant stop, to get the timer to stop. Can anyone help me with this? this is my email box hassan4allofus@yahoo.com

  • hussain

    Also i cant stop, to get the timer to stop. Can anyone help me with this? this is my email box muhammedhassan4islam@yahoo.com

  • hassan

    please guys how can i remove timer from counting or reading,i meant by using shutdown, to broswe.please guys this is my email box hassan4allofus@yahoo.com. thanks.

  • hassan

    please tom how can i apply the code,as you just saide early.please tom, this is my email box hassan4allofus@yahoo.com. thanks

  • juan

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

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

    thanks for the code!

  • jose

    How do you incorporate days into this? like a 30 day countdown…?

  • 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?

  • Jennifer

    I have the same question as Jose: How can I incorporate days into this?

  • 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

  • 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

  • dafydd1994

    great tut, but is there a way that i can get the timer to stop when a object crosses a certian point.

  • TG

    Hey man, this is awesome. I love all the flash stuff you make!

  • put if.0>i++{gotoAndPlay(ur frame)}
    that should work

  • Josh

    thx juan … your advice on stopping the timer REALLY helped alot … thx

  • 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

  • Ter

    Oh, the var in the pause button is called …
    pause
    which is in the formula in the play btn.

  • Ter

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

  • 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.

  • 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 :(

  • twyud

    hey man thank’s for tut, i like your flash stuff

  • 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

  • arthur

    Hi, I was wondering if anyone here knows how to restart the counter again, once it reaches 0.

  • enache

    hello
    please Ter can i have the code for you play\pause timer, i really really need him

  • 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

  • john

    Hello, i have a question…
    countdown = 7200000;<< this number”7200000″ how to load from external file?

  • suj

    Thanks so much! It would have taken me hours to figure this out ;)

  • steve

    Hi, Ter
    I am working on the pause btn aswell.
    Can you send you working version to vayphu1982@yahoo.com so I can play with my version.
    Thanks
    Steve

  • Nick

    Just wanted to say that Jeremy’s post works, just make it elapsed_time instead of time_elapsed. Thanks all.

  • Pingback: Understanding AS3 Timer Class : Emanuele Feronato()

  • yogsmca

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

  • 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

  • George

    What about when somthing pops up how do i do that
    ad when you click somthing it stops

  • Hi Ter, sorry to bother ya.
    Would you mind sending me your working version of the pause timer?
    My email is yew_yong@hotmail.com

    Thanks and happy new year.

  • konnichi wa

    hello every one,
    how to pause the count down?

  • t121hy

    hello,
    how to make action if after times is over then will go to another frame.
    please send me tutorial via email
    i want make quiz for my student
    thanks
    trydantry@yahoo.co.id

  • 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

  • ccmqv

    So do I have to add another frame so the time would stop.

    If so how do you add the second frame?

  • 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

  • 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);

  • 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?

  • JohnBoi

    Hey I need to know how to stop the timer from shaking?

  • Vahid

    JohnBoi, to stop the timer from shaking, use JUSTIFY property for dynamic txt.

  • 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!

  • 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?

  • 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

  • Pingback: FLASH – Contagem regressiva | Marcus Monteiro()

  • That works fine, does anyone knows how to make a timeline with an icon moving forward as the days goes by?

  • 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!

  • SS

    Thanks a million for this code.

  • jeece

    it does not work when used in a symbol, but works directly on the main scene. How to make it work in a symbol?

  • 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?

  • Pingback: 15 Countdown Timer | Code&Design-Studio()

  • Thanks for this tutorial. For those looking for as2 version follow here:
    timer in flash

  • Aguila

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

  • Monica

    This is an AWESOME tutorial, thanks.
    Is there a way to change it to 12hr clock & include am & pm?

  • Thank you very much !!, this counter is great my friend. !

  • 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.

  • Pingback: Understanding AS3 Timer Class « Gabriel's World()

  • 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

  • Gabriel

    Hi Kyle,

    Thank you for sharing the CountdownFX…it was really what I was looking for – plus I don’t have to put the time in the coding…sorry I am bit lasy :)

    Everybody needs to check it out!
    http://www.flashxml.net/countdown.html

  • Hemanth

    Hi

    Can u help me on how to stop the timer when the game is completed

  • KHAN

    please tell me how can i make countdown timer for 30 minuts
    give me complete coading pls

  • 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.

  • Pingback: [Download] Flash - Contador regressivo com action script - Marcus Monteiro()

  • This tutorial is great!!
    I use it in my Flash Project. Thank you very much for sharing it.

  • very good

  • 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..

  • Allen

    when i compleate the game, how to stop time of count_down and display the time in next frame?

  • william vargas

    hello, that’s very usefull for me, excellent!!

    god bless you

  • 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

  • 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

  • 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!

  • 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

  • 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

  • nice tutorial sir thanks a lot for providing useful information