Computer >> Computer tutorials >  >> Programming >> Javascript

How to set a countdown timer in javascript?


You can create a countdown timer in Javascript using the setInterval method. The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

To create a countdown, we need to check the difference between current time and final time and keep updating the countdown. For example,

Example

let countDownDate = new Date("Jul 21, 2020 00:00:00").getTime();
let x = setInterval(() => {
   let now = new Date().getTime();
   let distance = countDownDate - now;
   // Time calculations for days, hours, minutes and seconds
   let days = Math.floor(distance / (1000 * 60 * 60 * 24));
   let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
   let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
   let seconds = Math.floor((distance % (1000 * 60)) / 1000);
   console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s");
   // If the count down is finished, write some text
   if (distance < 0) {
      clearInterval(x);
      console.log("completed")
   }
}, 1000);

Output

This will give the output −

310d 0h 6m 46s
310d 0h 6m 45s
310d 0h 6m 44s
310d 0h 6m 43s
310d 0h 6m 42s
310d 0h 6m 41s
310d 0h 6m 40s
310d 0h 6m 39s
310d 0h 6m 38s
310d 0h 6m 37s
310d 0h 6m 36s
310d 0h 6m 35s
310d 0h 6m 34s
310d 0h 6m 33s