Like I mentioned earlier, setting a setTimeout is like marking a time
in the future for JavaScript to execute a statement. This is fine and
dandy when your setTimeout is something like this:
var the_timeout = setTimeout("alert('Hello!');", 60000);
Here you're telling JavaScript to wait one minute and then throw up a "Hello!" alert box. But what if you want to do something like this:
var the_string = "hello";
var the_timeout = setTimeout("alert(the_string);", 60000);
This tells JavaScript to wait one minute and throw up an alert box that contains whatever variable provided by the_string. So after a minute, JavaScript looks for a variable called the_string and calls alert() with that variable. The problem? In a minute's time, the_string
might contain something totally different from "Hello!"
In fact, if you had the above two lines of JavaScript inside a function,
the setTimeout would probably give you an error. For instance,
if you had a function like this:
function alertInAMinute()
{
var the_string = "hello";
var the_timeout = setTimeout("alert(the_string);", 60000);
}
And then you called the function inside a link like so:
<a href="#" onClick="alertInAMinute(); return false;">blah!</a>
This would probably produce an error because you defined the
variable called the_string inside the function using var. Remember: When you use var inside a function, as far as JavaScript is concerned, it exists only inside that function. This function creates a variable called the_string, sets the setTimeout, then exits.
Because you used var, the variable called the_string is erased
from JavaScript's memory. And then, when JavaScript looks for the_string in its memory a moment later, it's nowhere to be found, and you are dished up an error.
This problem occurs because you're passing a variable to setTimeout. Eliminate the problem by passing it the value
of the variable instead of the variable itself. Here's how:
function alertInAMinute()
{
var the_string = "hello";
var the_timeout = setTimeout("alert(" + the_string + ");",60000);
}
This code pulls the the_string variable out from inside the quotes
of setTimeout. And because the variable isn't in quotes, JavaScript
puts in the value of the variable.
You may be asking why I bothered with a variable in the first
place. Well, I'm simplifying things to make a point.
When you tackle today's homework, you'll see where this really makes a difference.
OK, enough of timers. As I said earlier, timers are used all over the place in dynamic HTML, so they're worth learning. If you want to learn more about dynamic HTML, be sure to check out Taylor's Dynamic HTML Tutorial.
Your JavaScript knowledge will serve you well, especially in
Lesson 3, when Taylor teaches you how to make stuff fly across your screen.
But don't get too swept up in multimedia merriment to make all this safe for the teeming millions who can't see dynamic HTML, you need to know how to detect what browsers your visitors are using.
next page»