How to Add Timing to Your HTML5 Game
reset(): This function initializes the timer and starts the elapsed time counter.
getCurrentTime(): This function returns the current system time at the moment it’s called. (Note that the time is in a special integer format, and it will not be recognizable by human readers.)
getElapsedTime(): Returns the number of seconds since the timer was created or the last reset (whichever is more recent).
For an example of timing, look at timerDemo.html:
This example demonstrates a simple timer. It displays the number of seconds the page has been running. The timer can be reset with the (cleverly named) Reset Timer button.
This program is relatively simple, but it illustrates some very powerful ideas. Use this process to build your own time-sensing game:
Create a variable for the timer.
This should be getting familiar. All the interesting elements are objects, and the timer is no exception. Create a variable called timer that will be an object of type Timer.
Reset the timer.
Be sure the timer starts out at zero.
Get the elapsed time in every frame.
In the update() function, call the timer’s getElapsedTime() method to find out how much time has passed and copy this value to the output area.
Reset the timer when the user presses the button.
When the user presses the reset button, call the timer’s reset() method to reset the elapsed time back to zero.
Hide the main scene.
This program uses the main loop from simpleGame, but it doesn’t really need to display the scene. For this reason, the Scene object has a hide() method. You can also display the scene later with its show() method.