最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught ReferenceError: hello is not defined - Stack Overflow

programmeradmin7浏览0评论

Any idea why I have the error Uncaught ReferenceError: hello is not defined ?

function hello() {
    console.log('hello ()');
    setTimeout("hello ()", 1000);
}
setTimeout("hello()", 1000);​

Here is a jsfiddle : /

Any idea why I have the error Uncaught ReferenceError: hello is not defined ?

function hello() {
    console.log('hello ()');
    setTimeout("hello ()", 1000);
}
setTimeout("hello()", 1000);​

Here is a jsfiddle : http://jsfiddle/s9vLk/

Share Improve this question edited Mar 24, 2012 at 7:11 Matthew asked Feb 28, 2012 at 1:55 MatthewMatthew 11.3k11 gold badges56 silver badges70 bronze badges 1
  • 1 Post your code on this site instead of on a different site. Links should be supplemental. – user1106925 Commented Feb 28, 2012 at 2:04
Add a ment  | 

4 Answers 4

Reset to default 4

The JavaScript code in your demo runs within the 'load' event handler (the option "onLoad" is selected). Therefore, the function hello is not a global function. You have to set the option to "no wrap (body)" or "no wrap (head)". That way, your JavaScript code will be global code.

Live demo: http://jsfiddle/s9vLk/1/

The problem is that you are passing strings to setTimeout() which means code in the string will effectively be evaled and thus isn't running in the scope you think it's running in and so the hello() function isn't found.

If you change the jsfiddle options on the left from "onload" to "no wrap" it works as is because then the function will be global rather than nested inside the onload handler, but a better option is to pass a function reference to setTimeout():

function hello() {
    console.log('hello ()');
    setTimeout(hello, 1000);
}
setTimeout(hello, 1000);

(Note: no parentheses after hello.)

You have a space between hello and the ().

You really should't pass the arguments as a string to setTimeout.

You don't (and shouldn't) need to reference your function name as a string.

function hello() {
    console.log('hello');
    setTimeout(hello, 1000);
}
setTimeout(hello, 1000);

Or better yet

setInterval(function() {
    console.log('hello');
}, 1000);
发布评论

评论列表(0)

  1. 暂无评论