we can create an simple countdown timer using javascript without any javascript library

for that first we need to create an html element with the following

<div id="timer">2:00</div>

And add the javacript code from below

<script type="text/javascript">
var timeoutHandle;
function countdown(minutes) {
    var seconds = 60;
    var mins = minutes
    function tick() {
        var counter = document.getElementById("timer");
        var current_minutes = mins-1
        seconds--;
        counter.innerHTML =
        current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
        if( seconds > 0 ) {
            timeoutHandle=setTimeout(tick, 1000);
        } else {

            if(mins > 1){

               // countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
               setTimeout(function () { countdown(mins - 1); }, 1000);

            }
        }
    }
    tick();
}

countdown(2);

</script>

countdown(2) is the function which invokes the timer and the minutes as the only parameter

and we are done!

The working example is shown below

2:00

Hope this helps to create simple countdown timer using javascript without any javascript library

As per the request from Steve i am adding the timer functionality in the format H:M:S

<div id="hms">00:10:10</div>

And add the javacript code from below

<script type="text/javascript">
    var timeoutHandle;
    function count() {

    var startTime = document.getElementById('hms').innerHTML;
    var pieces = startTime.split(":");
    var time = new Date();    time.setHours(pieces[0]);
    time.setMinutes(pieces[1]);
    time.setSeconds(pieces[2]);
    var timedif = new Date(time.valueOf() - 1000);
    var newtime = timedif.toTimeString().split(" ")[0];
    document.getElementById('hms').innerHTML=newtime;
    timeoutHandle=setTimeout(count, 1000);
}
count();

</script>

The working example is shown below

00:10:10

For the timer to continue on page refresh, you can use this code to store the time in cache and reuse that to start the timer

var timeoutHandle;
function countdown(minutes,stat) {
    var seconds = 60;
    var mins = minutes;
	 
	if(getCookie("minutes")&&getCookie("seconds")&&stat)
	{
		 var seconds = getCookie("seconds");
    	 var mins = getCookie("minutes");
	}
	 
    function tick() {
		
        var counter = document.getElementById("timer");
		setCookie("minutes",mins,10)
		setCookie("seconds",seconds,10)
        var current_minutes = mins-1
        seconds--;
        counter.innerHTML = 
		current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
		//save the time in cookie
		
		
		
        if( seconds > 0 ) {
            timeoutHandle=setTimeout(tick, 1000);
        } else {
             
            if(mins > 1){
                 
               // countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst    
               setTimeout(function () { countdown(parseInt(mins)-1,false); }, 1000);
                     
            }
        }
    }
    tick();
}
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}
 function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
countdown(2,true);

80 Comments on “Simple countdown timer using javascript

  1. Rahul
    October 11, 2013

    simply great..

  2. Rogara
    February 8, 2014

    Great, thanks a lot. 🙂

  3. Victor Streithorst
    February 10, 2014

    I don’t know if somebody else noticed this too, but the seconds never reach “00”. It jumps from “5:01” directly to “4:59”.

    I just changed the line:
    ‘ countdown(mins-1); ‘
    to:
    ‘ setTimeout(function () { countdown(mins – 1); }, 1000); ‘
    , and everything works like a charm now!

    Anyway, thank you! Your code saved me a lot of time!

    • navi
      February 11, 2014

      Thank you for you feedback and contribution

      • akshata.akkanna@gmail.com
        October 20, 2016

        Hello

        I have copy pasted the same code as you did but im getting just the constant value like 2:00

        • navaneeth
          October 25, 2016

          Please check the code again or paste them here

        • Brian Cooney
          July 1, 2017

          I had the same issue. My javascript code was running before the DOM was constructed. Make sure your script tag in HTML is after the CSS link.

          Wrap this around your code so it waits for DOM construction.

          window.onload = function() {
          // all of your code goes in here
          // it runs after the DOM is built
          }

          Hope that helps others out:)

  4. Todor
    April 19, 2014

    Great countdown!

    Can you please show how to increase the timer so it’s set for more than 2 minutes, maybe even hours and days? Thanks!

  5. Steve
    May 15, 2014

    This is great. How hard would it be to add a value for Hour? I’m trying to use this to for a 24 hour counter H:M:S

  6. navi
    June 26, 2014

    see the last section i added the code to show the format H:M:S
    http://navaneeth.me/simple-countdown-timer-using-javascript

  7. Manish Prabhakar
    August 12, 2014

    How to remove the timer when it reaches 0?

    • navi
      August 12, 2014

      Remove means?, Is this to remove the entire timer

      Inorder to add text when the timer expires please use this code


      function count() {
      var startTime = document.getElementById('hms').innerHTML;
      var pieces = startTime.split(":");
      var time = new Date(); time.setHours(pieces[0]);
      time.setMinutes(pieces[1]);
      time.setSeconds(pieces[2]);
      var timedif = new Date(time.valueOf() - 1000);
      var newtime = timedif.toTimeString().split(" ")[0];
      document.getElementById('hms').innerHTML=newtime;
      if(newtime!=='00:00:00'){
      setTimeout(count, 1000);
      }else
      {
      document.getElementById('hms').innerHTML='Ended';
      }

      }
      count();

      • Stan
        June 20, 2017

        This code is exactly what I need. However, where do I put the code in to change the timer from 0:00 to a message of my choice?

        Regards

  8. Ang
    December 11, 2014

    This is great!! Thank you so much for this!!! 🙂

  9. Simon
    December 19, 2014

    Thank you for this, it has really helped.

  10. Rushan
    January 6, 2015

    Excellant article…really helped us

  11. lev
    March 29, 2015

    is it posible to use it for each news with different countdown? like getting time from db. i tryed it but works only for first news.

    • navaneeth
      March 30, 2015

      You can use different id’s for the timer container to work that for multiple elements

  12. lev
    March 30, 2015

    yes but i mean use for 50, 100+ news and thats bad idea use different id’s. there’s any method to use foreach() function like php on javascript?

    • navaneeth
      April 1, 2015

      Just make the id to class ie “hms” and the html has to be repeated and just call the javascript function in a for loop or for each loop

  13. Marie
    March 30, 2015

    Very informative article

  14. prathysha
    June 8, 2015

    how to continue the same timer on page reload

    • navaneeth
      June 8, 2015

      Have to store the current time in session or cookie, then use that when reload happens

  15. priyanka
    June 15, 2015

    can you give me the code for timer using local storage

  16. priyanka
    June 16, 2015

    please give me the code for timer using local storage

    • navaneeth
      June 17, 2015

      you can use this code to store the time in cache and reuse that to start the timer

      function countdown(minutes) {
      var seconds = 60;
      var mins = minutes;

      if(getCookie("minutes")&&getCookie("seconds"))
      {
      var seconds = getCookie("seconds");
      var mins = getCookie("minutes");
      }

      function tick() {

      var counter = document.getElementById("timer");
      setCookie("minutes",mins,10)
      setCookie("seconds",seconds,10)
      var current_minutes = mins-1
      seconds--;
      counter.innerHTML =
      current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds); //save the time in cookie if( seconds > 0 ) {
      setTimeout(tick, 1000);
      } else {

      if(mins > 1){

      // countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
      setTimeout(function () { countdown(mins - 1); }, 1000);

      }
      }
      }
      tick();
      }
      function setCookie(cname,cvalue,exdays) {
      var d = new Date();
      d.setTime(d.getTime() + (exdays*24*60*60*1000));
      var expires = "expires=" + d.toGMTString();
      document.cookie = cname+"="+cvalue+"; "+expires;
      }
      function getCookie(cname) {
      var name = cname + "=";
      var ca = document.cookie.split(';');
      for(var i=0; i

      • raunit
        October 7, 2015

        time storage to cookie is not working

        • navaneeth
          December 9, 2015

          can u share me the code you used

  17. priyanka
    June 17, 2015

    above code not getting executed

  18. navaneeth
    June 17, 2015

    Have u copied the whole code??

  19. priyanka
    June 17, 2015

    yeah..i copied

    • navaneeth
      June 17, 2015

      pls send me the url where u pasted the code

  20. priyanka
    June 18, 2015

    i inserted the code in php program..it is in my pc..

    • navaneeth
      June 18, 2015

      Can u pls share me the code, so i can look in to it
      if you are running it in localhost
      you have to set the cookie domain to localhost

  21. priyanka
    July 10, 2015

    i am unable to post the code..can please give the whole program

    • navaneeth
      September 10, 2015

      Added the code to the last part of the post

  22. raja
    July 14, 2015

    i need local storage timer countdown please send me immediately.

    • navaneeth
      September 10, 2015

      Added the code to the last part of the post

  23. Janis
    September 1, 2015

    Hello, i intrested if its posoble and if is, you can plz tell how it do:?

    i whant make a php table wheri is listed a links, ect. whanted to set up cooldown time when i press a web page its aper to that link and start coldowntime from 2min, 4, 7, 20, 60, of eny links have eny colldowtime, and its starts only when i cliked the link, and apers in my page link table in section time left, when get to 0 its disapear(timer).

    • navaneeth
      September 10, 2015

      Explain pls, i cant get what you meant

  24. Aiswariya
    September 10, 2015

    The timer code is perfect ,but when i refresh my page its starts from first,i have to implement in my shopping site,Is there any solutions???

    • navaneeth
      September 10, 2015

      You have to store the values in database

  25. Erich Eachann
    September 17, 2015

    Is there a way to have the function execute twice?

    I’ve tried all of these but none of them work nicely:
    —————
    countdown(value1)
    countdown(value2)
    —————
    $.when(countdown(value1)).then(countdown(value2));
    —————
    $.when(countdown(work))
    .then(
    setTimeout(function() {
    alert(‘value2!’);
    countdown(value2);
    }, 2000))

    Any way to get this to work?

    • Erich Eachann
      September 17, 2015

      In other words,

      how do you wait for a first timer, then reset it and have a second timer execute?

      • navaneeth
        September 17, 2015

        HI

        Wait for the timer to complete and call another function when the time reaches 0

        • Erich Eachann
          September 17, 2015

          How do you integrate that in the original function (what code do I need)?

        • Madhu
          October 21, 2015

          In the 1st script, I changed 2, to 5 or 8.
          But the time always starts from 2:00

          • navaneeth
            December 9, 2015

            Share me the code you used

  26. Pol
    November 27, 2015

    Hello, I want to make a start button with audible warning and forward to updating the counter continued to work and did not start the first in a single session. In the third embodiment, like there is the possibility to make it through cookies for a day, but my knowledge is too small to make this code work – you could not see when you have free time? https://jsfiddle.net/HRrYG/

  27. dragonflai
    December 3, 2015

    Great work navaneeth, but i have some problem with your ‘cache’ version. I,ve used as is written but don’t work properly. Can you check or explain where i do a mnistake.

    please note: if you want add a reloading you can simple change this lines:
    instead of:
    document.getElementById(‘hms’).innerHTML=’Ended’;

    change with:
    document.getElementById(‘hms’).innerHTML=’Reloading Page…’;
    document.location.reload(true);

    on reload the counter is reset automatically. (reload all the page) 🙂

    — true of false – Is a Boolean flag, which, when it is true,
    causes the page to always be reloaded from the server.
    If it is false or not specified, the browser may reload the page from its cache.

  28. Joe
    December 7, 2015

    Hello Navaneeth,

    Just wondering why my timer stops after 1 minute.
    If I make it to count for 2 minutes it stops at 1:00
    If I make it to count for 60 minutes it stops at 59:00

    I am using the last code with cookies to store the count on page reload..thanks for help!

  29. Joe
    December 7, 2015

    Hello Navaneeth,

    Just wondering why my timer stops after 1 minute.
    If I make it to count for 2 minutes it stops at 1:00
    If I make it to count for 60 minutes it stops at 59:00

    I am using the last code with cookies to store the count on page reload..thanks for help!

  30. raju
    January 14, 2016

    Your cache version is not executing.. the time is refreshing on page reload…..can u please post the executed code…

    • navaneeth
      March 16, 2016

      are you trying it on local?

  31. gabriel
    February 26, 2016

    how to alert my user to finish countdown?

    • navaneeth
      March 17, 2016

      Just check the seconds if it has reached 0

  32. Seemanta Bhowmick
    March 26, 2016

    Hey there, the timer seems to stops at 1:00, if I set it to 2:00? Can you please help me out in solving this issue.. I’m a beginner at all this, so I would also like to know where and what code can I add to move a different page (say as moving to a result page, if exam time is up) when the timer is up?
    Thank you..any help would be really appreciated!

    • navaneeth
      April 2, 2016

      Pls post the code here, or mail me, will help you with this

  33. Nad
    May 20, 2016

    pls, when I try using For the timer to continue on page refresh, you can use this code to store the time in cache and reuse that to start the timer, the countdown just stop

    • navaneeth
      May 23, 2016

      i have updated the code, please check now

      • d laxmi
        November 14, 2016

        hiiii i need for the following code the time has been set to 1 min i need to set it for 2mins please help me i will send u the code here

        function isTimer(seconds) {
        // BUG: page refresh with keyboard triggers onkeyup and starts timer
        // Use restart button to reset timer

        let time = seconds;
        // only set timer once

        let one = $(“#timer > span”)[0].innerHTML;

        if (one == “1:00″) {

        let typingTimer = setInterval(() => {
        if (time <= 0) {

        clearInterval(typingTimer);

        } else {
        time -= 1;

        let timePad = (time span”)[0].innerHTML = `0:${timePad}`;

        }
        }, 1000);
        }
        else if (one == “0:00”) {return false;
        }

        return true;

        }

        • navaneeth
          December 19, 2016

          The first example shows the time set to 2 mins

  34. phani
    July 2, 2016

    plz send me all code
    my:phanikumar294@gmail.com

    • navaneeth
      July 6, 2016

      which code do you need?

  35. shail desai
    July 22, 2016

    thanks sir ,best help ever..better then any other website.

  36. vicky
    July 27, 2016

    Can you please send me the countdown spot left code

    Like i want user to show signup 15 spots left only and countdown slowly decreases its no like 14 after 8 seconds then 13 spots left after 8 or 10 seconds like that

    I need a code for such type I will be grateful to you if you can provide me such code

    Thanks alot in advance

    • navaneeth
      August 8, 2016

      Sorry for the delay, do you still need that code?

  37. Nelson C Joseph
    August 1, 2016

    how to reset timer during page refresh?

    • navaneeth
      August 8, 2016

      Use without the cookie option

  38. eko susilo
    August 2, 2016

    I use your timer to continue on page refresh, but when timer finish then i refresh page, the timer just show 0:00.

    01:10

    function countdown(minutes,stat) {
    var seconds = 60;
    var mins = minutes;

    if(getCookie(“minutes”)&&getCookie(“seconds”)&&stat)
    {
    var seconds = getCookie(“seconds”);
    var mins = getCookie(“minutes”);
    }

    function tick() {

    var counter = document.getElementById(“timer”);
    setCookie(“minutes”,mins,10)
    setCookie(“seconds”,seconds,10)
    var current_minutes = mins-1
    seconds–;
    counter.innerHTML =
    current_minutes.toString() + “:” + (seconds 0 ) {
    setTimeout(tick, 1000);
    } else {

    if(mins > 1){

    // countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
    setTimeout(function () { countdown(parseInt(mins)-1,false); }, 1000);

    }
    }
    }
    tick();
    }
    function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = “expires=” + d.toGMTString();
    document.cookie = cname+”=”+cvalue+”; “+expires;
    }
    function getCookie(cname) {
    var name = cname + “=”;
    var ca = document.cookie.split(‘;’);
    for(var i=0; i<ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1);
    if (c.indexOf(name) == 0) {
    return c.substring(name.length, c.length);
    }
    }
    return "";
    }
    countdown(2,true);

    • navaneeth
      August 8, 2016

      You have to reset the time back to the initial state when it expires, if you need them to work again

      • Bri
        October 22, 2016

        Could you tell how to reset time?

        • navaneeth
          October 25, 2016

          Just call the initiation function again

          • TG
            October 29, 2016

            Please how do i call the initation function again.. am trying it but its not working, please am waiting in anticipation for your favourable response, its urgent..

          • navaneeth
            December 29, 2016

            I have made small adjustments to the code
            Now call this before window.clearTimeout(timeoutHandle); countdown(2); when you want to initiate it again

  39. K.Srinivasa Rao
    October 25, 2016

    God bless you, dear Navi. May your tribe increase! Thank you for what you are doing.

  40. fmoh
    November 6, 2016

    Hi. nice script.
    I am using your script “as is”. I was trying to reset the timer by re-initializing the function (like you suggested i.e. countdown(2)), but when doing so, it does two things: 1) it sets a new timer counting down from init value and 2) it keeps old value running down as well. means, it keeps both values flickering downwards on same div container. any clue why this happens?
    thanks a lot

  41. GAJENDER
    December 2, 2016

    I WANT TO SET DATE TIMER IN MY PERSONAL WEBPAGE CAN U PL SEND ME CODE

    • navaneeth
      December 19, 2016

      Just simple one, or get me what exactly you need..
      The first section in the page shows a simple one
      Jsut create the html

      2:00

      and copy the script and call countdown(2);

  42. Rati
    July 26, 2017

    Thank you so much for the code! It works great…
    Is it possible to add some content (sound or at least notification “You time’s up” or something like that) after timer comes to 0?
    Tanks again!

Leave a Reply to priyanka Cancel reply

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