In this post, we are going to see how to write a JavaScript countdown timer.
Here is the JavaScript countdown timer script for you,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<!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: