Reputation: 15
Just got a short question, pretty straightforward, try simplify the answer as I am a novice when it comes to JS. Question is, why does the function inside the setTimeout require " " to function as intended, meaning that it fires itself every 5 seconds
var pal = document.getElementById("pal");
c=0;
function Tr(){
pal.innerHTML=c;
c=c+1;
setTimeout("Tr()", 5000);
}
Upvotes: 0
Views: 75
Reputation: 59232
It doesn't require it to be in quotes. But if it is in quotes, then it is eval
ed which is bad. But if it is in quotes it needs ()
but if it isn't a string then it shouldn't have it.
You can simply do this:
setTimeout(Tr, 5000);
setTimeout
recieves function to execute as its argument. If it is passed by function's name, then it directly called, but if it if given a string, it will evaluate it by using eval
.
Don't use strings as it uses eval
which is evil!!!
Upvotes: 1
Reputation: 39522
It doesn't, and in fact using it in quotes is not recommended as it uses eval()
.
The MDN defines window.setTimeout
as the following:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
var timeoutID = window.setTimeout(code, delay);
where
timeoutID
is the numerical ID of the timeout, which can be used later with window.clearTimeout().
func
is the function you want to execute after delay milliseconds.
code
in the alternate syntax is a string of code you want to execute after delay milliseconds (using this syntax is not recommended for the same reasons as usingeval()
)
Hence using functions
setTimeout(Tr, 5000)
and
setTimeout(function() { Tr(); });
would both work just as fine.
The latter with an anonymous function is used if you want to use parameters in your call - eg.:
var foo = 'bar';
setTimeout(function() { Tr('foo' + foo); }); // Will call Tr('foobar')
The reason why
setTimeout(Tr(), 5000)
does not work is because it first executes Tr()
and then calls setTimeout
with the result. If Tr()
returned the string 'foo'
, this call would call setTimeout('foo', 5000)
which makes no sense.
Upvotes: 1
Reputation: 156918
Because in contrary to other languages, like c#, you cannot pass a function call with parameters as parameter in JavaScript. You can pass a parameterless function though.
You pass in a string containing the parametrized function call or multiple functions you want to execute and the engine evaluates that at runtime.
See setTimeout - how to avoid using string for callback? to see it is possible to use a parameterless function as parameter.
Upvotes: 1
Reputation: 4465
setTimeout
accepts a function object. So you need to call it without the quotes and the function call parenthesis.
setTimeout(Tr, 5000);
Upvotes: 0