Creating a Countdown Timer
To create a countdown timer, we’ll use JavaScript to calculate the time difference between the current date and the target date. We’ll then update the timer every second to display the remaining time in days, hours, minutes, and seconds.
Example
Here’s an example of a countdown timer that counts down to a specific date and time:
<!-- Display the countdown timer in an element -->
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2030 15:37:25").getTime();
// Update the countdown every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Calculate the distance between now and the target date
var distance = countDownDate - now;
// Calculate days, hours, minutes, and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the countdown is over, display "EXPIRED"
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script> How It Works
Set the Target Date:
We define the target date and time usingÂnew Date("Jan 5, 2030 15:37:25"). TheÂgetTime()Â method converts this date into a timestamp in milliseconds.Update the Timer Every Second:
We useÂsetInterval to update the timer every second (1000 milliseconds).Calculate the Remaining Time:
Subtract the current time (
now) from the target time (countDownDate) to get the time difference (distance).Convert the difference into days, hours, minutes, and seconds using simple math operations.
Display the Timer:
The calculated time is displayed in an HTML element with the IDÂdemo.Handle Expiration:
If the countdown reaches zero (or goes negative), the timer stops, and the text “EXPIRED” is displayed.
