Java Reference
In-Depth Information
To clear a timer you use the window object's clearTimeout() method. This takes just one parameter,
the unique timer ID that the setTimeout() method returns.
Let's alter the preceding example and provide a button that you can click to stop the timer.
<!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');
}
function butStopTimer_onclick()
{
clearTimeout(timerID);
alert(“Timer has been cleared”);
}
</script>
</head>
<body onload=”window_onload()“>
<form name=”form1”>
<input type=”button” value=”Stop Timer” name=”butStopTimer”
onclick=”return butStopTimer_onclick()“ />
</form>
</body>
</html>
Save this as timertest2.htm and load it into your browser. Now if you click the Stop Timer button
before the three seconds are up, the timer will be cleared. This is because the button is connected to the
butStopTimer_onclick() function, which uses the timer's ID timerID with the clearTimeout()
method of the window object.
Try It Out Updating a Banner Advertisement
You'll now look at a bigger example using the setTimeout() method. The following example creates a
web page with an image banner advertisement that changes every few seconds.
<!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 language=JavaScript type=”text/javascript”>
var currentImgNumber = 1;
var numberOfImages = 3;
Search WWH ::




Custom Search