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
4 Answers
Reset to default 4The 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 eval
ed 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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744306511a4567739.html
评论列表(0条)