HTML and CSS Reference
In-Depth Information
provide an explanation of how to determine the number of seconds between two distinct events in a
running program.
A call to
Date()
generates an object with date and time information. The two lines
starttime = new Date();
starttime = Number(starttime.getTime());
store
the number of milliseconds (thousands of a second) since the start of 1970 in the variable
starttime
. (The reason JavaScript uses 1970 doesnt matter.)
When either of our two memory programs determines the game is over, it invokes
Date()
again as follows:
var now = new Date();
var nt = Number(now.getTime());
var seconds = Math.floor(.5+(nt-starttime)/1000);
This code
1.
creates a
new
Date
object and stores it in the variable
now
.
2.
extracts the time using
getTime
, converts it to
Number
, and assigns it to the variable
nt
. This
means
nt
holds the number of milliseconds from the start of 1970 until the point at which the
code called
Date
. The program then subtracts the saved starting time,
starttime
, from the
current time,
nt
.
3.
divides by 1,000 to get to seconds.
4.
adds
.5
and invokes
Math.floor
to round the result up or down to whole seconds.
If you need more precision than seconds provides, omit or modify the last step.
You can use this code whenever you need to calculate time elapsed between two events in a program.
Providing a pause
When we play memory using real cards, we dont consciously pause before flipping nonmatching cards
face down. But as noted earlier, our computer implementation must provide a pause so players have time
to see the two differing cards. You may recall from chapters 3 and 4 that the animation applications—
bouncing ball, cannonball, and slingshot—used the JavaScript function
setInterval
to set up events at
fixed time intervals. We can employ a related function,
setTimeout,
in our memory games. (To see the
complete code in context, go to the “Building the Application” section.) Lets see how to set up the event
and what happens when the pause time runs out.
The
setTimeout
function sets up a single event, which we can use to impose a pause. The
choose
function, called when a player clicks on the canvas, first checks the
firstpick
variable to determine if
the person has made a first or second selection. In either case, the program draws the card front on the
canvas in the same spot as the card back. If the click was a second choice and the two cards match, the
code sets the variable
matched
to
true
or
false
, depending on whether the cards did or didnt match. If
the application determines that the game isnt over, the code invokes
setTimeout(flipback,1000);