Java Reference
In-Depth Information
One-Shot Timer
Setting a one-shot timer is very easy: you just use the window object's setTimeout() method.
window.setTimeout(“your JavaScript code”, milliseconds_delay)
The method setTimeout() takes two parameters. The fi rst is the JavaScript code you want executed,
and the second is the delay, in milliseconds (thousandths of a second), until the code is executed.
The method returns a value (an integer), which is the timer's unique ID. If you decide later that you
want to stop the timer fi ring, you use this ID to tell JavaScript which timer you are referring to.
For example, to set a timer that fi res three seconds after the page has loaded, you could use the follow-
ing code:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<script type=”text/javascript”>
var timerID;
function window_onload()
{
timerID = setTimeout(“alert('Times Up!')“,3000);
alert('Timer Set');
}
</script>
</head>
<body onload=”window_onload()“>
</body>
</html>
Save this fi le as timertest.htm, and load it into your browser. In this page a message box appears
3,000 milliseconds (that is, 3 seconds) after the onload event of the window has fi red.
The setTimeout() method can also take a direct reference to a function instead of a JavaScript string.
For example if you have a function called myFunction then you call setTimeout() like this:
window.setTimeout(myFunction, milliseconds_delay)
Although setTimeout() is a method of the window object, you'll remember that because the window
object is at the top of the hierarchy, you don't need to use its name when referring to its properties and
methods. Hence, you can use setTimeout() instead of window.setTimeout().
It's important to note that setting a timer does not stop the script from continuing to execute. The timer
runs in the background and fi res when its time is up. In the meantime the page runs as usual, and any
script after you start the timer's countdown will run immediately. So, in this example, the alert box telling
you that the timer has been set appears immediately after the code setting the timer has been executed.
What if you decided that you wanted to stop the timer before it fi red?
Search WWH ::




Custom Search