Main Page

Intervals and timeouts

<a href=”javascript:goSomewhere(1,2,3,4)” onmouseover=”window.status=’Information
on Wrox books.’ “>Books</a>
Intervals and timeouts
Java developers are familiar with the
method of objects, which causes the program to stop and
wait a specified amount of time before continuing on to the next line of code. This is a very useful piece
of functionality and, unfortunately, one that JavaScript doesn’t support. But all is not lost. You have a
couple of ways around this issue.
JavaScript supports timeouts and intervals, which effectively tell the browser when certain code should
be executed: Timeouts execute the given code after a specified number of milliseconds; intervals execute
the given code repeatedly, waiting a specified number of milliseconds in between.
Setting a timeout is done using the
method. This method accepts two arguments:
the code to execute and the number of milliseconds (1/1000 of a second) to wait before executing it. The
first argument can either be a string of code (as would be used with the
function) or a pointer to a
function. For example, both these lines display an alert after one second:
setTimeout(“alert(‘Hello world!’) “, 1000);
setTimeout(function() { alert(“Hello world!”); }, 1000);
Of course, you can also reference a previously defined function:
function sayHelloWorld() {
alert(“Hello world!”);
setTimout(sayHelloWorld, 1000);
When you call
, it creates a numeric timeout ID, which is similar to a process ID in an
operating system. The timeout ID is essentially an identifier for the delayed process should you decide,
after calling
, that the code shouldn’t be executed. To cancel a pending timeout, use the
method and pass in the timeout ID:
var iTimeoutId = setTimeout(“alert(‘Hello world!’)”, 1000);
You may be thinking to yourself, “Why would I define a timeout and then cancel it before it executes?”
Consider the tooltips available in most applications today. When you move your mouse over a button, it
Be careful not to overuse the status bar and thereby making it a distraction. For
example, many sites still use the scrolling message code that scrolls text across the
status bar. Not only is this a fairly useless trick, it’s also annoying, very unprofes-
sional, and adds a very amateurish feeling that a Web site or Web application can do
without. Because this book is all about professional JavaScript, the scrolling text
code will not be covered. However, if you are interested in playing around with
scrolling text, check out
, where you
can find a large number of these scripts.
Chapter 5
08_579088 ch05.qxd 3/28/05 11:37 AM Page 146

JavaScript EditorFree JavaScript Editor     Ajax Editor