BOUNCING BALL
It is often the case that you want to indicate the passage of time on the screen. The following example will
display 0, 1, .... etc. with the number changing every second.
This is a good example for you to take the time to write and run, both because it showcases timing events
and also because it will make you appreciate how long a second lasts. The code takes the value out of the
secs input field in the form named f, converts that value to a number, adds 1 to that number, and then
converts it back to a string to assign as the value of the secs element. Try replacing the single statement
inside the increase function with the statement
document.f.secs.value = 1+document.f.secs.value;
and see what happens. This is a lesson in the difference between numbers and character strings. Please
play around with this little example. If you want to make the numbers go up in smaller increments, change
the 1000 to 250 and the 1 to .25. This makes the script show quarter-second changes.
If you want to allow your code to stop a particular event, you can set up a global variable (one thats
outside of any function). I use a variable named tev, my shorthand for timing event.
var tev;
You would then modify the setInterval call to be:
tev = setInterval(moveball,100);
When you wanted to stop this event, youd include this code:
clearInterval(tev);
To reiterate, the setInterval function sets up a timing event that keeps occurring until it is cleared. If
you know you want an event to happen just once, the setTimeout method sets up exactly one event. You
can use either method to produce the same results, but JavaScript furnishes both to make things easier.
For the bouncing ball application, the moveball function calculates a new position for the ball, does the
calculations to check for collisions and when they occur, redirects the ball and draws a new display. This
is done over and over—the calls to moveball keep happening because we used setInterval.