Countdown Timer
by sbhomra
HTML
<div id="container">
<div id="timer">
-.--
</div>
<br />
<div id="message"></div>
<br />
<button id="btn-start-timer">Start Countdown</button>
<button id="btn-stop-timer" style="display:none">Stop Countdown</button>
<button id="btn-reset-timer" style="display:none">Reset Countdown</button>
</div>
CSS
#container {
padding: 2em;
text-align: center;
}
#timer {
font-size: 6em;
}
JavaScript
const Timer = {
ClockPaused: false,
TimerStart: 10,
StartTime: null,
TimeRemaining: 0,
EndTime: null,
HtmlContainer: null,
"Start": function(htmlCountdown) {
Timer.StartTime = (new Date()).getTime() - 0;
Timer.EndTime = (new Date()).getTime() + Timer.TimerStart * 1000;
Timer.HtmlContainer = $(htmlCountdown);
// Ensure any added styles have been reset.
Timer.HtmlContainer.removeAttr("style");
Timer.DisplayCountdown();
// Ensure message is cleared for when the countdown may have been reset.
$("#message").html("");
// Show/hide the appropriate buttons.
$("#btn-stop-timer").show();
$("#btn-start-timer").hide();
$("#btn-reset-timer").hide();
},
"DisplayCountdown": function() {
if (Timer.ClockPaused) {
return true;
}
Timer.TimeRemaining = (Timer.EndTime - (new Date()).getTime()) / 1000;
if (Timer.TimeRemaining < 0) {
Timer.TimeRemaining = 0;
}
//Display countdown value in page.
Timer.HtmlContainer.html(Timer.TimeRemaining.toFixed(2));
//Calculate percentage to append different text colours.
const remainingPercent = Timer.TimeRemaining / Timer.TimerStart * 100;
if (remainingPercent < 15) {
Timer.HtmlContainer.css("color", "Red");
} else if (remainingPercent < 51) {
Timer.HtmlContainer.css("color", "Orange");
}
if (Timer.TimeRemaining > 0 && !Timer.ClockPaused) {
setTimeout(function() {
Timer.DisplayCountdown();
}, 100);
}
else if (!Timer.ClockPaused) {
Timer.TimesUp();
}
},
"Stop" : function() {
Timer.ClockPaused = true;
const timeTaken = Timer.TimerStart - Timer.TimeRemaining;
$("#message").html("Your time: " +...