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

若如初见. 提交于 2019-12-18 09:54:09

问题


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?


回答1:


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);



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3741503/what-causes-function-is-not-defined-when-passing-a-string-to-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!