(code found at https://hotwired.lycos.com/webmonkey/98/29/index2a.html) |
|
A simple stop watch | |
Clock |
To get a timer working in a loop, you have to write a function that calls
itself. Happily, this is possible in JavaScript. Here's an example:
var the_count = 0;
This works, whereas the infinite hell-freezing-over loop on the last page didn't, because infinite "while" loops lock the browser up and prevent anything from happening during the execution of the loop. This setTimeout trick makes sort of a slow loop. In the above example, the browser has two seconds to do things between each iteration. How to Cancel a setTimeout Now that you know how to make a timer loop run infinitely, you'll probably want to know how to stop it. This is the magic of clearTimeout. If you look at the HTML of the timer on the previous page, you'll see the following form element: <input type="button" value="stop timer" This is the button you hit to stop the timer. The command to stop a setTimeout
is clearTimeout(), which is actually quite simple. When you set a setTimeout
like this, you can cancel it like this: |
|
|
|
The time is now: Click on the start clock button to turn the clock on. This clock reads the time off your computer and then updates the textbox every half second. I'm showing you this for two reasons. First, it's another example of making a timer by having a function call itself. Second, it shows you a little more about the Date object, which I mentioned back when we covered cookies. |
Here's the code: function writeTime() { // ask the object for some information // fixTime makes the minutes and seconds look right // put together the time string and write it out // run this function again in half a second }
if (the_time <10) It might look a little long, but that's just because it's well commented. Let's go through the code line by line. var today = new Date(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); minutes = fixTime(minutes); The next two lines put the string together and write it to the form element.
the_timeout = setTimeout('writeTime();', 500); |