Java Reference
In-Depth Information
are more images to show, and so you set another timer going, identical to the one you set in the window
object's onload event handler. This timer will call this function again in three seconds.
In earlier browsers, this was the only method of creating a timer that fi red continually at regular intervals.
However, in most current browsers such as IE6+ and Firefox, you'll see next that there's an easier way.
Setting a Timer that Fires at Regular Intervals
Modern browsers saw new methods added to the window object for setting timers, namely the
setInterval() and clearInterval() methods. These work in a very similar way to setTimeout()
and clearTimeout() , except that the timer fi res continually at regular intervals rather than just once.
The method setInterval() takes the same parameters as setTimeout() , except that the second
parameter now specifi es the interval, in milliseconds, between each fi ring of the timer, rather than just
the length of time before the timer fi res.
For example, to set a timer that fi res the function myFunction() every fi ve seconds, the code would be
as follows:
var myTimerID = setInterval(“myFunction()”,5000);
As with setTimeout() , the setInterval() method returns a unique timer ID that you'll need if you
want to clear the timer with clearInterval() , which works identically to clearTimeout() . So to
stop the timer started in the preceding code, you would use the following:
clearInterval(myTimerID);
Try It Out World Time Converter (Part 2)
Let's change the world time example that you saw earlier, so that it displays a local time and selected
city time as a continually updating clock.
You'll be making changes to the WorldTimeConverter.htm fi le, so open that in your text editor. Add
the following function before the functions that are already defi ned:
var daylightSavingAdjust = 0;
function window_onload()
{
updateTimeZone();
window.setInterval(“updateTime()”,1000);
}
function updateTimeZone()
{
Next edit the <body> tag so it looks like this:
<body onload=”return window_onload()”>
Resave the fi le, and then load WorldTimeConverter.htm into your browser. The page should look the
same as the previous version of the time converter, except that the time is updated every second.
Search WWH ::




Custom Search