Skip to content

JavaScript timer countdown with seconds | Example code

  • by

To create a JavaScript timer countdown use setInterval method. It’s a JavaScript built-in function that takes two arguments – a function, callback, and an integer, timeout. SetInterval will call the function you give it every timeout millisecond.

For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.

function makeAlert(){ 
    alert("Popup window!");
};

setInterval(makeAlert, 500);

JavaScript timer countdown with seconds

A simple example code creates a simple js countdown timer that goes from “05:00” to “00:00” and then resets to “05:00” once it ends.

<!DOCTYPE html>
<html>
<body>
 <div>Registration closes in <span id="time">05:00</span> minutes!</div>
</body>
<script>
  function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
      minutes = parseInt(timer / 60, 10);
      seconds = parseInt(timer % 60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      display.textContent = minutes + ":" + seconds;

      if (--timer < 0) {
        timer = duration;
      }
    }, 1000);
  }

  window.onload = function () {
    var fiveMinutes = 60 * 5,
    display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
  };

</script>
</html>

Output:

JavaScript timer countdown with seconds

Alternatively, this will create a text countdown. Countdown 10 seconds


<body>
 <div id="countdown"></div>
</body>
<script>
  var timeleft = 10;
  var downloadTimer = setInterval(function(){
    if(timeleft <= 0){
      clearInterval(downloadTimer);
      document.getElementById("countdown").innerHTML = "Finished";
    } else {
      document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
    }
    timeleft -= 1;
  }, 1000);
</script>

Output: 7 seconds remaining

Comment if you have any doubts or suggestions on this JS timer topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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