Create a countdown timer using setInterval

SetInterval is a very usefull function when making webpages that should look ‘alive’. I am here going to make a countdown timer using the setInterval and clearInterval functions:

First we need two variables:

var clock = 10; //Start value of counter
var countdownId = 0; // Id of counter

Now we need the countdown function to call every interval:

function countdown() {
    if(clock > 0) {
        clock = clock - 1;
        document.getElementById('cdDiv').innerHTML = clock;
    }
    else {
        // Stop timer
        clearInterval(countdownId);
    }
}

Now we need a div to show the timer in:

<div id="cdDiv">10</div>

Now we put it all togheter:

<html>
  <head>
    <title>My little countdown timer</title>
    <script type="text/javascript">
        var clock = 10;
        var countdownId = 0;

        function start() {
            //Start clock
            countdownId = setInterval("countdown()", 1000);
        }

        function countdown(){
            if(clock > 0){
                clock = clock - 1;
                document.getElementById('cdDiv').innerHTML = clock;
            }
            else {
                //Stop clock
                clearInterval(countdownId);
            }
        }
    </script>
  </head>
  <body onload="start()">
      <div id="cdDiv">10</div>
  </body>
</html>

This small example is mostly so I remember the clearInterval function name which keeps escaping me 🙂

  1. Very useful for my JS videogame, thank you 🙂

  2. What is the purpose of assigning countdownID here:

    countdownId = setInterval(“countdown()”, 1000);

    I cant see why, and it runs fine with just:

    setInterval(“countdown()”, 1000);

    Cheers

    • Yes that is true. I just have as a practice to always save the interval id so that I can use it to remove the interval later

  3. Ah i see, its assigned to a variable so we can identify it when we need to clear the interval. Sorry 🙂

Reply to Niklas ¬
Cancel reply


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.