Need a countdown timer without having to download third party libraries or install additional npm packages?
I did too.
Ideally, and essentially, all I needed was a function to accept a target end date and return the remaining time until that date. That’s exactly what I built using only pure (vanilla) JavaScript. I’ll show you the code and then explain, line-by-line. :)
Let’s explain what’s going on here:
function countdown(`endDate`) {
Ok, softball line of code here right? We’re declaring our function countdown
which accepts a parameter endDate
. So far, so good, yeah?
let days, hours, minutes, seconds;
Now we’re declaring several variables that we’ll need. These will be the units of time that will be calculated and displayed. Note: These were the specific units I needed; You can add/remove other units of time as needed for your purposes.
Here, I chained two methods to transform endDate
into a usable format that we can perform operations on.
First:
endDate = new Date(endDate)
converts our passed in endDate
parameter into a JavaScript Date object.
Second:
.getTime();
returns our newly converted JavaScript date into milliseconds…Specifically, the number of milliseconds that have elapsed between 1 January 1970 00:00:00 UTC and the given date.
Great! Now our endDate
is in milliseconds and ready to be used in calculations. Before we start calculating though, I added a simple validation check:
if (isNaN(endDate)) {
return;
}
After our conversions, we want to make sure the resulting number is, in fact a number. If not, we end the show right here. Ok, now we’re done setting up the basics, now we can start having fun.
setInterval(calculate, 1000);
Since we are evaluating how much time is remaining every second, we’ll use setInterval
to repeatedly execute some function we decide to give it. So in the code above, we pass in our calculate function as the first argument and 1000
as the second argument to denote one second (1000 ms = 1 second).
Now we can declare our calculate
function…
function calculate() {
let startDate = new Date().getTime();
…and then grab the exact date as of this moment, converted into milliseconds, and place it in variable called startDate
.
Then we can determine the time remaining between the current date and our end date:
let timeRemaining = parseInt((endDate - startDate) / 1000);
To do this, we subtract startDate
from endDate
to get the remaining milliseconds between the two. Then we divide by 1000
to get seconds, which will be an easier unit to work with for calculating our other units of time. We store this in a variable called timeRemaining
.
Now we check to see that there is, in fact, still time remaining between the current date and our end date:
if (timeRemaining >= 0) {
If there is, we move into this block and calculate the unit specific measurements of time we want to display. Let’s start with remaining days:
days = parseInt(timeRemaining / 86400);
To calculate the days remaining, we divide our remaining time by 86400
, the number of seconds in a single day. This result is then parsed within the parseInt()
function to ensure we work with whole numbers.
Before we continue calculating the other units, we need to subtract the days we’ve already calculated:
timeRemaining = (timeRemaining % 86400);
Once we do this, we assign the remaining time to our timeRemaining
variable.
We can now continue calculating the other units of time in the same manner:
hours = parseInt(timeRemaining / 3600); // 3600 seconds in one hour
timeRemaining = (timeRemaining % 3600);
minutes = parseInt(timeRemaining / 60); // 60 seconds in one minute
timeRemaining = (timeRemaining % 60);
seconds = parseInt(timeRemaining);
Almost done! We’re now ready to update our DOM elements with our newly calculated units of time!
I made things easier for myself and created an element per unit of time I was going to display. For reference, check out my GitHub repo to see the page I built utilizing this countdown timer. In essence, my timer would be displayed in a div
that looked like this:
<div class="countdown">
<p class="timer">
<span id="days"></span> Day(s)
<span id="hours"></span> Hour(s)
<span id="minutes"></span> Minute(s)
<span id="seconds"></span> Second(s)
</p>
</div>
With that in mind, I simply get the element I need and set its innerHTML
to the appropriate unit:
document.getElementById("days").innerHTML = parseInt(days, 10);
For remaining days, I parse my days
variable and explicitly set the radix to 10
before assigning it to my element. This is to ensure the resulting display is set in the decimal numeral system.
Continuing on with the other units of time, I adjust the resulting calculations to display a leading zero before assigning it to its corresponding element:
document.getElementById("hours").innerHTML = hours < 10 ? "0" + hours : hours;
First, I check if the remaining hours are below double-digits, which start at 10. If it is, I append a "0"
before the remaining hours. Otherwise, I just return the remaining hours as-is.
For example, if hours = 4
, the ternary operator would evaluate to true
as it's less than 10. Adding the leading zero would return "04"
.
Alternatively, if hours = 23
, the ternary operator would evaluate to false
, so adding the leading zero would be unnecessary. So, I just return the hours as-is.
I do the same thing for minutes
and seconds
:
document.getElementById("minutes").innerHTML = minutes < 10 ? "0" + minutes : minutes;
document.getElementById("seconds").innerHTML = seconds < 10 ? "0" + seconds : seconds;
Just need a few more closing curly bracket and remaining code to end function execution if there is no time remaining:
} else {
return;
}
}
}
And that’s it!
In the context of my maintenance page, I wanted this countdown timer to start on page load. So I decided to place my countdown
function within an iife, or immediately-invoked function expression:
(function () {
countdown('04/01/2018 05:00:00 PM');
}());
Our scheduled platform upgrade was slated to end on April 1st (no joke!) at 5PM, so this was the date I passed in.
This worked perfectly and was just what I needed. As promised, no external libraries or extra packages were used. JavaScript really is a wonderful language. :)
Thanks for reading! If you enjoyed it, please let me know in a comment below. Or even better, if you feel this article was thorough in a good way, please share it/tweet it to spread the knowledge and love. ♥️
For more from me, be sure to follow my blog! And to see what I'm currently up to, follow me on Twitter && Instagram!