Timeouts and Intervals
The setTimeout( )
method of the
Window object
schedules
a piece of JavaScript code to be run
at some specified
time in the future. The clearTimeout( )
method can
be used to cancel the execution of that code. setTimeout( )
is commonly used to perform animations or other kinds of
repetitive actions. If a function runs and then uses
setTimeout( )
to schedule itself to be called
again, we get a process that repeats without any user intervention.
JavaScript 1.2 has added the
setInterval( )
and
clearInterval( )
methods, which are like
setTimeout( )
and
clearTimeout( )
,
except that they automatically reschedule the code to run repeatedly;
there is no need for the code to reschedule itself.
The setTimeout( )
method is commonly used in
conjunction with the status
or
defaultStatus
properties to animate some kind of
message in the status bar of the browser. In general,
animations involving the status bar are
gaudy, and you should shun them! There are, however, a few
status-bar animation techniques
that can be useful and in good taste. Example 13-2
shows such a tasteful status-bar animation. It displays the current
time in the status bar and updates that time once a minute. Because
the update occurs only once a minute, this animation does not produce
a constant flickering distraction at the bottom of the browser
window, like so many others do.
Note the use of the onload
event handler of the
<body>
tag to perform the first call to the
display_time_in_status_line( ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.