In my last two blog posts I’ve talked about the countdown clock that I was making to be able to use in OBS. It came to my attention that I needed to make some changes to it. The purpose of the countdown clock was to use in a stream and have it counting down the time till September 28th at 10PM Central time. While researching online I found that I can set the timer to countdown to a specific time by using the Date class and the .getTime function. First I needed to create a new variable for the date that I was targeting.
var countDownDate = new Date("September 28, 2021 22:00:00").getTime();
Then I needed to create a variable for the current time and the time remaining and add them to a function.
var myfunc = setInterval(function () {
var now = new Date().getTime();
var timeleft = countDownDate - now;
After that it was time for the calculations. In my previous Countdown clocks I was getting the proper numbers but I was getting them incorrectly. The problem I was having was that I was getting the days, hours, numbers, and minutes, but the numbers weren’t decrementing correctly. I needed to use the % operator used for getting remainders of dividing as follows.
var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);
After that all I had to do was set my innerHTML to the proper variables and set up a clearInterval function for the counter once it reaches 0 and everything was set.
document.getElementById("days").innerHTML = days + " Days";
document.getElementById("hours").innerHTML = hours + ":";
document.getElementById("minutes").innerHTML = minutes + ":";
document.getElementById("seconds").innerHTML = seconds + ":";
if (timeleft < 0) {
clearInterval(myfunc);
document.getElementById("days").innerHTML = "";
document.getElementById("hours").innerHTML = "";
document.getElementById("minutes").innerHTML = "";
document.getElementById("seconds").innerHTML = "";
document.getElementById("end").innerHTML = "LET'S RACE!!!!!";
}
}, 1000);
I’ve spent the better part of three weeks exploring different ways to implement this timer and I’m happy to finally be done with it. Thankfully now, I can move on to something a little more powerful and dynamic. Till next time, thanks for reading!