This post will describe how to create a JavaScript countdown timer using a reusable class. The jQuery library is used in this example because of its popularity, however it is very easy to amend the class to just use pure JavaScript.
To start with, two of the very basic components needed to implement the timer on a web page include the element
responsible for containing the timer. The second component is the end date
which is the cut off date when the timer should stop.
To begin, you can create a simple HTML document with a <span>
element containing the countdown timer.
An example of how this document might look can be seen below.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <p>Hey! This sale ends in <span id="timer"></span></p> </body> </html>
As seen from the markup above, <span id="timer">
will be used as the element.
Create a basic JavaScript class that passes the end date
and element
parameters into its constructor.
For the purpose of this article, the class can simply reside in an inline script within the HTML document.
<script type="text/javascript"> class MyTimer { constructor(date, element) { this.date = new Date(date).getTime(); this.element = jQuery(element); } } </script>
As seen above, the date
and element
properties are set to the timestamp of the end date and the element used to display the countdown respectively.
Within the constructor, the text to display the ‘day’, ‘hour’, ‘minute’ and ‘second’ text is set. Also included are the singular names such as hour
which is used when the timer displays 1 hour
rather than 1 hours
.
constructor(date, element) { this.date = new Date(date).getTime(); this.element = jQuery(element); this.dayText = 'day'; this.daysText = 'days'; this.hourText = 'hour'; this.hoursText = 'hours'; this.minuteText = 'minute'; this.minutesText = 'minutes'; this.secondText = 'second'; this.secondsText = 'seconds'; }
The JavaScript will contain three methods.
The first method, getNowTime()
will be used to get the current time of the user viewing the countdown clock.
<script type="text/javascript"> class MyTimer { constructor(date, element) { this.date = new Date(date).getTime(); this.element = jQuery(element); this.dayText = 'day'; this.daysText = 'days'; this.hourText = 'hour'; this.hoursText = 'hours'; this.minuteText = 'minute'; this.minutesText = 'minutes'; this.secondText = 'second'; this.secondsText = 'seconds'; } getNowTime() { return new Date().getTime(); } }
Secondly, a startTimer()
will be used to initialise the countdown timer.
<script type="text/javascript"> class MyTimer { constructor(date, element) { this.date = new Date(date).getTime(); this.element = jQuery(element); this.dayText = 'day'; this.daysText = 'days'; this.hourText = 'hour'; this.hoursText = 'hours'; this.minuteText = 'minute'; this.minutesText = 'minutes'; this.secondText = 'second'; this.secondsText = 'seconds'; } getNowTime() { return new Date().getTime(); } startTimer() { var _self = this, now = _self.getNowTime(), timeDifference = _self.date - now; // Avoid delay upon updating timer _self.updateTimer(_self); // Update the countdown every 1 second var timerInterval = setInterval(function() { _self.updateTimer(_self); }, 1000); // When the countdown is finished, stop updating the timer if (timeDifference && timeDifference < 0) { clearInterval(timerInterval); } } } </script>
The actual code to update the timer element within the page resides in the updateTimer()
method.
Looking at the above code, the updateTimer()
method is contained within JavaScript’s setInterval()
allows the countdown timer to update every second.
To avoid the one second delay where the timer doesn’t initially display on the webpage, the updateTimer()
method is run first outside of setInterval()
.
The updateTimer()
method contains the following code.
updateTimer(_self) { var now = _self.getNowTime(), timeDifference = _self.date - now; var days = Math.floor((timeDifference / (1000 * 60 * 60 * 24)) % 7), hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)), minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)), seconds = Math.floor((timeDifference / 1000) % 60); var dayText = (days !== 1) ? _self.daysText : _self.dayText, hourText = (hours !== 1) ? _self.hoursText : _self.hourText, minuteText = (minutes !== 1) ? _self.minutesText : _self.minuteText, secondText = (seconds !== 1) ? _self.secondsText : _self.secondText; var content = days + ' ' + dayText + ' ' + hours + ' ' + hourText + ' ' + minutes + ' ' + minuteText + ' ' + seconds + ' ' + secondText; _self.element.html(content); }
A timeDifference
variable holds the value of the difference in time between the current timestamp and the end date
timestamp.
From this timeDifference
variable, the amount of days, hours, minutes and seconds can be calculated. These values are stored within the days
, hours
, minutes
and seconds
variables respectively.
We then check if the singular or plural text should be used to display in the timer. For example, if the hours remaining equals 1, show hour
for 1 hour
and not 1 hours
.
The time remaining is then concatenated into a content
variables, and the HTML element is updated with the content.
The countdown timer can then be initialised using the following lines of code.
var timer = new MyTimer('2018-02-20 17:50:00', '#timer'); timer.startTimer();
A complete example of the code might look like the following.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <p>Hey! This sale ends in <span id="timer"></span></p> <script type="text/javascript"> class MyTimer { constructor(date, element) { this.date = new Date(date).getTime(); this.element = jQuery(element); this.dayText = 'day'; this.daysText = 'days'; this.hourText = 'hour'; this.hoursText = 'hours'; this.minuteText = 'minute'; this.minutesText = 'minutes'; this.secondText = 'second'; this.secondsText = 'seconds'; } getNowTime() { return new Date().getTime(); } startTimer() { var _self = this, now = _self.getNowTime(), timeDifference = _self.date - now; // Avoid delay upon updating timer _self.updateTimer(_self); // Update the countdown every 1 second var timerInterval = setInterval(function() { _self.updateTimer(_self); }, 1000); // When the countdown is finished, stop updating the timer if (timeDifference && timeDifference < 0) { clearInterval(timerInterval); } } updateTimer(_self) { var now = _self.getNowTime(), timeDifference = _self.date - now; var days = Math.floor((timeDifference / (1000 * 60 * 60 * 24)) % 7), hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)), minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)), seconds = Math.floor((timeDifference / 1000) % 60); var dayText = (days !== 1) ? _self.daysText : _self.dayText, hourText = (hours !== 1) ? _self.hoursText : _self.hourText, minuteText = (minutes !== 1) ? _self.minutesText : _self.minuteText, secondText = (seconds !== 1) ? _self.secondsText : _self.secondText; var content = days + ' ' + dayText + ' ' + hours + ' ' + hourText + ' ' + minutes + ' ' + minuteText + ' ' + seconds + ' ' + secondText; _self.element.html(content); } } var timer = new MyTimer('2018-02-20 17:50:00', '#timer'); timer.startTimer(); </script> </body> </html>