How to set a countdown timer in javascript?


We can set a countdown timer in JavaScript using the setInterval() method. This method continuously calls a function or executes a code snippet with a fixed time delay between every call.

The setInterval() method calls a function at described intervals in milliseconds. It continues calling the function until the clearInterval() is called, or the window is closed.

Syntax

Following is the syntax of this method −

setInterval(function, milliseconds);

The setInterval method accepts two parameter functions and milliseconds.

  • function − A function containing a block of code designed to perform a particular task.

  • milliseconds − it is the time interval between the execution of the function.

This method returns a positive integer representing the interval ID.

Example

In the following example, we are creating a countdown Timer from a Jan 1, 2027 12:12:50 to the current time.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>countDownTimer</title>
   <style>
      h3 {
         text-align: center;
         margin-top: 0px;
      }
   </style>
</head>
<body>
   <h3 id="time"></h3>
   <script>
      // set the date we are counting down to
      var countDown = new Date("jan 1, 2027 12:12:50").getTime();
     
      //update the count down in every 1 second
      var update = setInterval(function () {
     
         // get the today's date and time
         var now = new Date().getTime();
       
         //find the difference b/w countDown and now
         var diff = countDown - now;
       
         //now we are calculating time in days, hrs, minutes, and seconds.
         var days = Math.floor(diff / (1000 * 60 * 60 * 24));
         var hrs = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
         var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
         var seconds = Math.floor((diff % (1000 * 60)) / 1000);
       
         //now output the result in an element with id ="time"
         document.getElementById("time").innerHTML =
         days + "-D: " + hrs + "-H: " + minutes + "-M: " + seconds + "-S ";
         if (diff < 0) {
            clearInterval(update);
            document.getElementById("time").innerHTML = "Expired";
         }
      }, 1000);
   </script>
</body>
</html>

Updated on: 19-Dec-2022

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements