The following code is presented, in the book Head First jQuery.
function lightning_one(t) {
$("#lightning1").fadeIn(250).fadeOut(250);
setTimeout("lightning_one()", t);
}; // end lightning_one
It gets called with this line.
lightning_one(3000);
The observed behaviour is that the lightning fades in and out once, waits 3 seconds, fades in and out again, and then continues to fade in and out. Firebug shows no javascript errors.
I understand why I see what I see. I thought I would attempt to preserve the 3 second interval, so I changed this:
setTimeout("lightning_one()", t); // nothing in the brackets
to this:
setTimeout("lightning_one(t)", t); // t is in the brackets
When I refresh the page, the lightning fades in and out once. Firebug tells me that variable t is undefined.
My question is, if the variable t is not defined after my change, how did the command run without error before I changed it? It still has a variable named t.
More Info
Thank you everyone who wrote comments and answers. For the record, in the “end” folder, the code becomes this:
lightning_one();
function lightning_one(){
$("#container #lightning1").fadeIn(250).fadeOut(250);
setTimeout("lightning_one()",4000);
};
I haven’t finished the applicable chapter yet so I don’t know if the code change gets suggested later on. As mentioned earlier, this might not be the best book out there. However it’s the one I bought and I am learning the fundamentals of jQuery from it.
Because the first argument of
setTimeoutas a string iseval-ed, meaning that it will looking into the outer scope of the function in whichtis not defined. The first one is fine because you don’t use any variables in the call, but the second is not becausetis not defined outside the scope of the function. It is in fact local.Advice: Don’t use
evalat all. In fact, you don’t need the string argument. Use a function expression: