Main Page

History

Here, the code uses linked timeouts, meaning that the code being executed by
setTimeout()
also calls
setTimeout()
. If
iNum
is still not equal to
iMax
after it is incremented, another
setTimeout()
call is
made. You don’t have to keep track of the timeout ID or clear it because after the code is executed, the
timeout ID is destroyed.
History
It is possible to access the history of a browser window. The history is the list of places the user has been.
For security reasons, all you can do is navigate through the history; there is no way to get the URLs of
the pages contained in the browser history.
To navigate through history, you don’t need a time machine; you use the
window
object’s
history
prop-
erty and its associated methods.
The
go()
method takes only one parameter: the number of pages to go back or forward. If the number is
negative, you are going backwards through the browser history. If the number is positive you are going
forward (think of it as the difference between the Back and Forward buttons).
So, to go back one page, the following code can be used:
window.history.go(-1);
Of course, the reference to the
window
object isn’t necessary, so this will do:
history.go(-1);
Most often, this is used to create a custom “Back” button embedded in a Web page, such as:
<a href=”javascript:history.go(-1)”>Back to the previous page</a>
To go forward one page, just use a positive one:
history.go(1);
Alternatively, you can use the
back()
and
forward()
methods to accomplish the same thing:
//go back one
history.back();
//go forward one
history.forward();
These may be a little more meaningful because they accurately reflect the behavior of the browser Back
and Forward buttons.
So which method should you use? It’s really depends on the use case. To wait a cer-
tain amount of time before executing a certain set of code, use timeouts. If, however,
you need some code to be executed repeatedly, then use intervals.
148
Chapter 5
08_579088 ch05.qxd 3/28/05 11:37 AM Page 148


JavaScript EditorFree JavaScript Editor     Ajax Editor


©