Java Reference
In-Depth Information
In the updateTime() function, you saw that it uses the function getTimeString() to format the time
string. Let's look at that function now. This function is passed a Date object as a parameter and uses it
to create a string with the format hours : minutes : seconds .
function getTimeString(dateObject)
{
var timeString;
var hours = dateObject.getHours();
if (hours < 10)
hours = “0” + hours;
var minutes = dateObject.getMinutes();
if (minutes < 10)
minutes = “0” + minutes;
var seconds = dateObject.getSeconds()
if (seconds < 10)
seconds = “0” + seconds;
timeString = hours + “:” + minutes + “:” + seconds;
return timeString;
}
Why do you need this function? Well, you can't just use this:
getHours() + “:” + getMinutes() + “:” + getSeconds()
That won't take care of those times when any of the three results of these functions is less than 10. For
example, 1 minute past noon would look like 12:1:00 rather than 12:01:00.
The function therefore gets the values for hours, minutes, and seconds and checks each to see if it is
below 10. If it is, a zero is added to the front of the string. When all the values have been retrieved, they
are concatenated in the variable timeString before being returned to the calling function.
In the next section, you're going to look at how, by adding a timer, you can make the displayed time
update every second like a clock.
Timers in a Web Page
You can create two types of timers: one-shot timers and continually fi ring timers. The one-shot timer triggers
just once after a certain period of time, and the second type of timer continually triggers at set intervals. You
will investigate each of these types of timers in the next two sections.
Within reasonable limits, you can have as many timers as you want and can set them going at any point
in your code, such as at the window onload event or at the click of a button. Common uses for timers
include advertisement banner pictures that change at regular intervals or display the changing time in
a web page. Also all sorts of animations done with DHTML need setTimeout() or setInterval() —
you'll be looking at DHTML later on in the topic.
Search WWH ::




Custom Search