简体   繁体   中英

What causes “function is not defined” when passing a string to setTimeout?

var my_new_function = function(){
----
};
window.setTimeout(my_new_function, 1600);

the above works properly without any errors.

when i use:

window.setTimeout("my_new_function()", 1600);

it's working properly, but firebug is showing error :

my_new_function is not defined

in some articles about setTimeout, i found calling functions like in the 1st method, and in some other articles, i saw the other method.

which is more correct? and why is firebug showing such an error?

When you call the function with

window.setTimeout(my_new_function, 1600);

You are setting the reference to the function.

The function in your second setTimeout example

window.setTimeout("my_new_function()", 1600);

needs to be evaluated when it is executed. When it is evaluated it is being executed in global scope. So if the function is in local scope the browser will not find it. [Sounds like this is your issue]

Seasoned developers will not recommend using strings in setTimeout since they need to be evaluated each time. All that means is it takes longer to execute.

Another option to call setTimeout is

window.setTimeout( function(){ my_new_function(); }, 1600);

It doesn't matter which you use. If you pass a string, it will be turned into a function when the timer is fired. The first method looks a lot cleaner to me, though.

Note that passing a string runs it in window scope, so functions and other local variables may not be present and will fail.

window.setTimeout("my_new_function()", 1600);

doesn't work because it is equivalent to:

window.setTimeout("window.my_new_function()", 1600);

and there's no such function defined in the window scope. You are declaring it in a local variable scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM