Java Reference
In-Depth Information
<title>Chapter 7, Example 5</title>
</head>
<body>
<div id="output"></div>
<script>
function updateTime() {
document.getElementById("output").innerHTML = new Date();
}
setInterval(updateTime, 1000);
</script>
</body>
</html>
Save this file as ch7 _ example5.html , and load it into your browser.
In the body of this page is a <div /> element, and its id attribute has the value of output :
<div id="output"></div>
The updated date and time will be displayed inside this element, and the contents of this element are
updated by the updateTime() function:
function updateTime() {
document.getElementById("output").innerText = new Date();
}
This function uses the document.getElementById() method to retrieve the aforementioned <div/>
element, and it uses the innerText property to set the element's text to a new Date object. When
displayed in the browser, JavaScript converts the Date object to a human‐readable string containing
both the date and time.
To change the date and time, you use the setInterval() function, passing it a reference to the
updateTime() function, and setting it to execute every second (1,000 milliseconds). This, in turn,
changes the text inside of the <div/> element, thus showing the current date and time every second.
That completes your look at this example and also your introduction to timers. You use the
setInterval() and clearInterval() functions in later chapters.
summarY
You started the chapter by looking at Coordinated Universal Time (UTC), which is an international
standard time. You then looked at how to create timers in web pages.
The particular points covered were the following:
The Date object enables you to set and get UTC time in a way similar to setting a Date
object's local time by using methods (such as setUTCHours() and getUTCHours() ) for setting
and getting UTC hours with similar methods for months, years, minutes, seconds, and so on.
 
Search WWH ::




Custom Search