This is an example of a JavaScript solution to Exercise[20].
New stopwatch!
// CODE DUMP
/*
* Timer is a constructor function that may be
* used to produces instances of objects of
* type Timer. An object of type Timer has
* methods start() and stop() that start
* and stop a timer, a method called reset
* that resets a timer, and a method called
* elaspedTimeInMs that returns an amount of
* elapsed time. If a timer has been started
* but not stopped, then elapsedTimeInMs
* returns the amount of time (in milliseconds)
* that has elapsed since the timer was started.
* If a timer has been started and stopped,
* then elapsedTimeInMs returns the amount of
* time that elapsed between the time the
* timer was started and stopped.
*/
function Timer() {
this.reset();
}
Timer.prototype = {
reset: function() {
this.timeStarted = null;
this.timeStopped = null;
},
start: function() {
this.timeStarted = new Date();
},
stop: function() {
this.timeStopped = new Date();
},
elapsedTimeInMs() {
if (this.timeStarted != null) {
if (this.timeStopped != null) {
return this.timeStopped - this.timeStarted;
}
else {
return new Date() - this.timeStarted;
}
}
else {
return undefined;
}
}
};
/*
* pause does nothing for timeInMs millisends
* before returning control to the code that
* called pause. Internally, pause uses a
* Timer object to wait the specified
* amount of time before completing.
*/
function pause(timeInMs) {
var timer = new Timer();
timer.start();
while (timer.elapsedTimeInMs() < timeInMs);
}
var stopwatch = new Timer();
var stopwatchIsRunning = false;
function output(message) {
console.log(message);
var display = document.getElementById("display");
display.innerHTML = message;
}
function showCode() {
var code = document.getElementById("code");
code.setAttribute("style", "display:inline")
}
function hideCode() {
var code = document.getElementById("code");
code.setAttribute("style", "display:none")
}
function startStopwatch() {
if (stopwatchIsRunning) {
output("3");
pause(1000);
output("2");
pause(1000);
output("1");
pause(1000);
output("Snap!");
showCode();
stopwatchIsRunning = false;
}
else {
hideCode();
stopwatch.start();
stopwatchIsRunning = true;
output("Stopwatch is running...");
}
}
function stopStopwatch() {
stopwatch.stop();
stopwatchIsRunning = false;
output("Stopwatch has been stopped.");
}
function resetStopwatch() {
hideCode();
stopwatch.reset();
stopwatchIsRunning = false;
output("Stopwatch has been reset.");
}
function displayElapsedTime() {
hideCode();
output("Elapsed time (ms): " + stopwatch.elapsedTimeInMs());
}