Countdown Timer showing hundredths of seconds
This code is an example of my ATimer class added to the code of one of the jQuery forum's users' . The hundredths of seconds are updated every 20mS because the user will not perceive anything faster (biological constraints, and screen refresh rate constraint)
by Jason Schutz
HTML
<button onclick="doStart()">Start</button>
<div id="CountDownPanel"></div>
CSS
#CountDownPanel {
height: 200px;
width: 200px;
text-size: 6em;
}
.warn { color: red; }
JavaScript
//This example is has three sections of code. The first is the page-specific code, the second is some helpers, and the third is my customer ATimer class...
//(1) Page code
var WARNING_THRESHOLD = 4 * 60 * 1000; //4 minutes (in milliseconds)
function doStart() {
var id = "CountDownPanel";
var i = 600; //duration in seconds (10 minutes)
ActivateCountDown(id, i);
}
function ActivateCountDown(strContainerID, initialValue) {
var _countDownContainer = document.getElementById(strContainerID);
var $_countDownContainer;
if (!_countDownContainer) {
alert("count down error: container does not exist: " + strContainerID +
"\nmake sure html element with this ID exists");
} else {
$_countDownContainer = $(document.getElementById(strContainerID));
//the ATimer below works with time values in milliseconds
//the "20" will update display ever 20 milliseconds, as fast as screen refreshes
$_countDownContainer.removeClass("warn");
var timerID = new ATimer(initialValue * 1000, 20, CountDownComplete, CountDownTick);
timerID.start();
}
function CountDownComplete() {
alert("Your time has expired!");
}
function CountDownTick(remaining) {
if (remaining < WARNING_THRESHOLD) $_countDownContainer.addClass("warn");
SetCountdownText(remaining);
}
function SetCountdownText(remaining) {
_countDownContainer.innerHTML = remaining.millisecondsToHundredthsString();
}
}
//(2) Helpers
Number.prototype.millisecondsToHundredthsString = function () {
/// <summary>Convert number of milliseconds into text with format MM:SS:hh</summary>
/// <param name="this">Number of milliseconds</param>
/// <returns type="Text" >Duration, text in format MM:SS:hh</<returns>
var partMultipliers = [{ d: 60000, p: 100 }, { d: 1000, p: 100 }, { d: 10, p: 100}];
var remainder = parseInt(this);
return partMultipliers.reduce(function...