Main Page

given code

takes a little bit of time before that friendly yellow box appears to tell you what the button does. If you
move your mouse over the button for just a short time and then move it to another button, the tooltip
isn’t displayed. This is precisely why you would cancel a timeout before the code executes: Because you
want to wait a specified amount of time before the code is executed. If the user does something that
would result in a different outcome, you need the flexibility to cancel that timeout.
Intervals work in much the same way except that they repeat the given code indefinitely at specific time
intervals. To set up an interval, use the
method with the same type of arguments as you
use with
— the code to execute and the number of milliseconds to wait between each
execution. For example:
setInterval(“alert(‘Hello world!’) “, 1000);
setInterval(function() { alert(“Hello world!”); }, 1000);
function sayHelloWorld() {
alert(“Hello world!”);
setInterval(sayHelloWorld, 1000);
Also similar to timeouts, the
method creates an interval ID to identify the code to be exe-
cuted. It can be used with the
method to prevent any further executions. Obviously,
this is much more important when using intervals because, if left unchecked, they continue to execute
until the page is unloaded. Here is a common example of interval usage:
var iNum = 0;
var iMax = 100;
var iIntervalId = null;
function incNum() {
if (iNum == iMax) {
iIntervalId = setInterval(incNum, 500);
In this code, the number
is incremented every 500 milliseconds until it reaches the maximum
), at which point the interval is cleared. You can use timeouts for this, eliminating the need to keep
track of a timeout ID, by doing the following:
var iNum = 0;
var iMax = 100;
function incNum() {
if (iNum != iMax) {
setTimeout(incNum, 500);
setTimeout(incNum, 500);
JavaScript in the Browser
08_579088 ch05.qxd 3/28/05 11:37 AM Page 147

JavaScript EditorFree JavaScript Editor     Ajax Editor