This is an example of a JavaScript solution to Exercise[20].
<!-
The following HTML markup and embedded JavaScript
code has been tested in version 53.0.2785.143 m of
the Chrome web browser and might not work as intended
in other versions of Chrome or in other web browsers.
->
<script>
var popupWindow;
function openPopup() {
waitForIt(2000);
popupWindow = window.open("", "", "width=200,height=100");
popupWindow.document.write("Surprise!");
}
function closePopup() {
if (popupWindow != undefined) {
popupWindow.close();
}
}
/*
* 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) {
// Previously missing code starts here:
var timer = new Timer();
timer.start();
// Previously, missing code ends here.
while (timer.elapsedTimeInMs() < timeInMs);
}
function waitForIt(delay) {
alert("Wait for it...");
pause(delay);
}
</script>
<button onclick="openPopup()">open</button>
<button onclick="closePopup()">close</button>