Java Reference
In-Depth Information
<head>
<title>Chapter 7, Example 4</title>
</head>
<body>
<script>
function doThisLater() {
alert("Time's up!");
}
var timerId = setTimeout(doThisLater, 3000);
clearTimeout(timerId);
</script>
</body>
</html>
Save this as ch7 _ example4.html and load it into your browser. You will not see an alert box
displaying the Time's up! message because you called clearTimeout() and passed the timer ID before
the timeout could expire.
setting a timer that Fires at regular intervals
The setInterval() and clearInterval() functions work similarly to setTimeout() and
clearTimeout() , except that the timer fires continually at regular intervals rather than just once.
The setInterval() function takes the same parameters as setTimeout() , except that the second
parameter now specifies the interval, in milliseconds, between each firing of the timer, rather than
just the length of time before the timer fires.
For example, to set a timer that fires the function myFunction() every five seconds, the code would
be as follows:
var myTimerID = setInterval(myFunction,5000);
As with setTimeout() , the setInterval() method returns a unique timer ID that you'll need if you
want to clear the timer with clearInterval() , which works identically to clearTimeout() . So to
stop the timer started in the preceding code, you would use the following:
clearInterval(myTimerID);
a Counting Clock
trY it out
In this example, you write a simple page that displays the current date and time. That's not very
exciting, so you'll also make it update every second:
<!DOCTYPE html>
<html lang="en">
<head>
 
Search WWH ::




Custom Search