The key to being able to prevent a future event set by
setTimeout(function, timeout)
to happen is 1) use
the fact that this function returns an event id; 2) assign this event id
to a variable; 3) use clearTimeout(event_id)
to
cancel that future event.
Since doing so effectively stops the animation, and since
essentially all games allow the user to stop them, we might as well
implement a stop()
function which will be used to
cancel future events via the clearTimeout()
call.
Furthermore, we add a stop button by modifying the
html code, which you can always look at by clicking on the
image above.
The fact that we needed to add a way to stop the animation indicates that we may not always be aware of all the code that is running in the background. What happens if we are playing this game in a browser and switch to a different tab? Is the code still running? If so, does it impact the performance of our browser, especially when we have multiple tabs?
While browsers are becoming "smarter" in the way they deal with
code running in a background, a new standard is emerging to replace
setTimeout()
by something better. If you want, you
can read what
Paul Irish
and
Jerome Etienne wrote on that topic
and try to implement this code yourself. I will not do so since,
as I am writing this, the cancelRequestAnimationFrame method does not work
for the latest version of Firefox (8.0 beta). However, perhaps this will
work by the time you are reading this, and you could improve the animation
that way.
Note how the above code is getting rather long. What I will do next, is to move parts of that code inside the html editor (which you can also do right now by simply cut-and-pasting it from the editor above into the html editor) so that we can focus on the parts that change only.
I will also implement a way to pause the animation, by adding a third button and the relevant javascript code. Why don't you try to do the same right now, before reading the next section?
Keep your personal notes here. These notes are stored by your browser on your own computer, and will be available from any page on this site. You can choose to use html syntax for formatting.