In this post, we are going to see how to write a JavaScript countdown timer.
Here is the JavaScript countdown timer script for you,
//JS code for countdown timer
function countdownTimer() {
const difference = +new Date('2023-10-11') - +new Date();
let remaining = "Time's up!";
if (difference > 0) {
const parts = {
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
minutes: Math.floor((difference / 1000 / 60) % 60),
seconds: Math.floor((difference / 1000) % 60)
};
remaining = Object.keys(parts)
.map(part => {
if (!parts[part]) return;
return `${parts[part]} ${part}`;
})
.join(" ");
}
document.getElementById("countdown").innerHTML = remaining;
}I have given a complete demo script with the HTML for you to test this script right away.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Timer</title>
<style>
body {
background: linear-gradient(90deg, rgba(135,129,244,1) 0%, rgba(44,44,190,1) 37%, rgba(14,171,203,1) 100%);
}
h1{
text-align: center;
color: white;
}
h2 {
color: white;
}
</style>
</head>
<body>
<!-- Timer -->
<h1> <div id="countdown"></div> </h1>
<!-- JS Countdown timer -->
<script>
//JS code for countdown timer
function countdownTimer() {
const difference = +new Date('2023-10-11') - +new Date();
let remaining = "Time's up!";
if (difference > 0) {
const parts = {
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
minutes: Math.floor((difference / 1000 / 60) % 60),
seconds: Math.floor((difference / 1000) % 60)
};
remaining = Object.keys(parts)
.map(part => {
if (!parts[part]) return;
return `${parts[part]} ${part}`;
})
.join(" ");
}
document.getElementById("countdown").innerHTML = remaining;
}
countdownTimer()
setInterval(countdownTimer, 1000);
</script>
</body>
</html>This script is simple to understand. A little JavaScript knowledge is enough for this.
You can also see the working demo of this script from the below link:
