USE TIMERS
Timers can be used on a Web page to have a block of code execute after a
specified amount of time. The easiest way to create a timer is with the
setTimeout() method of the window object, for
example:
setTimeout ("code to execute", milliseconds_delay);
The two parameters are:
- the code that you want to execute when the timer fires
- the time delay in milliseconds until the timer fires
So, how do you call a timer function? Most often, event handlers are used for
this purpose, for example, onload to trigger a function when the
page loads, or onclick to trigger a function when a button is
clicked.
Event handlers are covered in detail in Lesson 6, but for now, the simplest
way to do this is to use an onload event in the
<body> tag and call a function that contains the timer.
First define the function in the head section of the page, for example:
<script type="text/javascript" language="JavaScript">
<!--
function startTime() {
timer = setTimeout('var tday = new Date();
alert ("Today is " + tday)',5000);
// sets a delay of 5000 milliseconds, or 5 seconds
}
// -->
</script>
</head>
then add an onload event to call the function:
<body onload = "startTime()">
You can also use a function name in place of the actual code in the
setTimeout statement:
function startTime() {
var tday = new Date();
alert("Today is " + tday);
}
timer = setTimeout("startTime()",5000);
Moving On
In this lesson, you learned more about displaying date and time on a Web page. You also learned how to use arrays, and how to create a JavaScript timer. In Lesson 6, you'll learn about events, and how to use events to create image rollovers and dynamic text changes. Before you move on, don't forget to do the assignment and take the quiz. In addition, visit the Message Board to find out what your fellow students are up to.
