Today, I wanted to make a simple countdown timer, you know, like for New Year’s or something. I’ve named it “zzz countdown” ’cause, well, it’s kinda basic, and I was feeling sleepy.
First, I fired up my code editor. Nothing fancy, just a plain HTML file to start. I needed a place to show the countdown, so I threw in a div with an ID. I figured I’d grab that later with JavaScript.
Setting up the HTML
My HTML was pretty barebones:
<div id="countdown"></div>
Yep, that’s it. Just one div. All the magic was gonna happen in the script.
The JavaScript Part
Okay, so now for the JavaScript. First thing, I needed to get today’s date and the target date (like New Year’s). I used the Date object for that. It’s built-in, so, super convenient.
let today = new Date();
let targetDate = new Date('January 1, 2025 00:00:00');
I hardcoded the target date for now. I’ll probably make that adjustable later, maybe with an input field or something.
Next up, I needed to calculate the difference between those two dates. I got the time in milliseconds for both, subtracted them, and then did some math to get days, hours, minutes, and seconds.
Lots of dividing and remainders there. The thing just chops off the decimals, giving me whole numbers.
Making it Tick
I wanted the countdown to update every second, right? So, I used setInterval(). It’s a function that runs another function repeatedly after a set amount of time. I set it to 1000 milliseconds, which is one second.
setInterval(updateCountdown, 1000);
updateCountdown is my function to re-calculate and to show the time.
Inside the updateCountdown function, I basically did all that date math again, and then I updated the HTML of that div I mentioned earlier.
Grab the countdown div:*(‘countdown’)
Set it is innerHTML:* = …
function updateCountdown() {
let today = new Date();
let timeDiff = *() - *();
//Do the math same with above...
let countdownElement = *('countdown');
* = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
I just mashed together the days, hours, minutes, and seconds with some letters to make it readable. Put “d”, “h”, “m”,”s” behind them.
And… that’s pretty much it! I saved the file, opened it in my browser, and boom, a working countdown timer. It’s not the prettiest thing, but it works! I might add some styling later, maybe some animations, but for now, I’m happy with my little “zzz countdown”. It was a fun little project to kill some time.