Java Reference
In-Depth Information
<title>Chapter 7, Example 3</title>
</head>
<body>
<script>
function doThisLater() {
alert("Time's up!");
}
setTimeout(doThisLater, 3000);
</script>
</body>
</html>
Save this file as
ch7 _ example3.html
, and load it into your browser.
This page displays a message box three seconds after the browser executes the JavaScript code in the
body of the page. Let's look at that code starting with the
doThisLater()
function:
function doThisLater() {
alert("Time's up!");
}
This function, when called, simply displays a message in an
alert
box. You delay the call of this
function by using
setTimeout()
:
setTimeout(doThisLater, 3000);
Take note how
doThisLater()
is passed to
setTimeout()
—the parentheses are omitted. You do not
want to call
doThisLater()
here; you simply want to refer to the function object.
The second parameter tells JavaScript to execute
doThisLater()
after 3,000 milliseconds, or 3 seconds,
have passed.
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 fires 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 fired?
To clear a timer you use the
clearTimeout()
function. This takes just one parameter: the unique
timer ID returned by the
setTimeout()
function.
Stopping a Timer
trY it out
In this example, you'll alter the preceding example and provide a button that you can click to stop the timer:
<!DOCTYPE html>
<html lang="en">