function init() {
setInterval(function_to_call, 1000);
}
The first parameter to setTimeout and setInterval is a function. Passing it a string means it has to first eval() the string into a function before it can run it.
window.onload = init;
function init() {
//do other stuff here
function_to_call();
}
function function_to_call() {
//do something
setTimeout(function_to_call, 2000);
}
function init() {
setTimeout(function_to_call, 1000);
}
The first parameter to setTimeout needs to be a function. If you pass it a string then the browser has to convert the string into a function before it can pass the function to the setTimeout.
Repeat to yourself ten thousand times so you don’t forget: “setTimeout takes a function and not a string - never ever use a string to represent a function”.
I beg to differ here. The correct syntax is either
setTimeout(“script Expression”,msecs[, language]) or,
setTimeout(functionReference,msecs[, arg1, …argN])
One of the major ones is that a whole new instance of the javascript environment must be created for the purpose of evaluating the result of the string. Not only is that a major performance hit, it’s also a wasteful use of eval due to it providing no benefit over that of correctly assigning the function instead.
There are also security reasons too, such as if the string is not completely trusted.
Documentation sites such as Mozilla’s javascript reference for setTimeout help to make this clear too.
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 using eval())