In this post, we will learn how to create a countdown timer with JavaScript. The countdown timer counts time from the current time to the future time. So how we can create countdown timer, we will learn in this post. 


How To Create A Countdown Timer With JavaScript ?


Create A Countdown Timer

To create a countdown timer with JavaScript, we use some JavaScript methods. We use  Date  object to work with dates and times. 

We use  getTime()  method, this method returns time in milliseconds. 

We use  Math.floor()  function, this function returns the largest integer value that is less than or equal to a number. 

We use  setInterval()  method, this method repeats a given function at every given time-interval. In our case we will run the function in every one second. 

And last we use  clearInterval()  method, this method clears the interval which has been set by the setInterval() method.  


Now we create countdown timer and understand this given code:


<!DOCTYPE HTML>
<html>
<head>
<title>How To Create A Countdown Timer With JavaScript ?</title>
<style>

#showCountdowntimer {
text-align: center;
font-size: 30px;
}

</style>
</head>
<body>

<div id="showCountdowntimer"></div>

<script>

// Set any future date and convert into milliseconds

var futureDate = new Date("May 17, 2021 15:37:25").getTime();


// Run the countdown timer in every 1 second

var countdownTimer = setInterval(function() {


// Get current day date and time and convert into milliseconds

var currentDate = new Date().getTime();


// Find the difference between futureDate and currentDate

var difference = futureDate - currentDate;


// Time calculations in days, hours, minutes and seconds and rounds the number to its near integer

var days = Math.floor(difference / (1000 * 60 * 60 * 24));
var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((difference % (1000 * 60)) / 1000);


// Output the result

document.getElementById("showCountdowntimer").innerHTML = days + "Days " + hours + "Hours "

+ minutes + "Minutes " + seconds + "Seconds ";


// If the count down timer ends then show this text

if (difference < 0) {
clearInterval(countdownTimer);
document.getElementById("showCountdowntimer").innerHTML = "TIMER EXPIRED";
}
}, 1000);

</script>
</body>
</html> code-box



Summary

In this post we learned how to create a countdown timer with JavaScript. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post