Reputation: 19482
I saw this question, and I'm wondering what is the problem with this?
var id = 12;
setTimeout( showGrid ( 'i want to pass variable ' + id + ' here' ), 5000 );
I read the question I'm interested in what the code above is not a good solution. I've only Chrome installed, I've tried it and it works. Is there any browser issue with it?
Why the anonymous function is better?
Upvotes: 2
Views: 328
Reputation: 1038720
You could use a closure:
var id = 12;
setTimeout(function() {
showGrid('i want to pass variable ' + id + ' here');
}, 5000);
And here's a live demo.
edit(Milo) from the comments:
the setTimeout function expects a callback or a string variable. You are not passing such thing so your code is invalid. You are directly invoking the showGrid function which is not how it is supposed to work. The showGrid function should be invoked only 5 seconds later.
Upvotes: 5
Reputation: 20235
setTimout
expects a function as its first argument and a time as its second argument, then optional arguments to pass to the function. So, if you have a function:
function showGrid( str ) {
return str;
}
and you have the following setTimeout
:
setTimeout( showGrid( "..." ), 5000 );
then you are calling showGrid
and passing the return value to setTimeout
, so it ends up like this:
// "..." is returned from showGrid( "..." )
setTimeout( "...", 5000 );
and "..."
is not a function. So there are two ways to get around this, you can make an enclosure (as in Darin's answer), or add the argument after the time.
setTimeout( function() {
showGrid( "..." );
}, 5000 );
// same thing
setTimeout( showGrid, 5000, "..." );
Example: http://jsfiddle.net/fFg57/
Upvotes: 2
Reputation: 6052
var id = 12;
setTimeout( "showGrid ( 'i want to pass variable " + id + " here' )", 5000 );
the first parameter takes a string, much like what you would pass to a eval
function.
and notice the Small o
in setTimeout
Upvotes: 1