Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - setTimeout - how to avoid using string for callback?

When using setTimeout, you have to put the code you want to execute into a string:

setTimeout('alert("foobar!");', 1000);

However, I want to execute a function to which I have a reference in a variable. I want to be able to do this:

var myGreatFunction = function() { alert("foobar!"); };
// ...
setTimeout('myGreatFunction();', 1000);

(Though in real life, the alert is a lengthier bit of code and myGreatFunction gets passed around as a parameter to other functions, within which the setTimeout is called.)

Of course, when the timeout triggers, myGreatFunction isn't a recognised function so it doesn't execute.

I wish javascript let me do this, but it doesn't:

setTimeout(function() { myGreatFunction(); }, 1000);

Is there a nice way round this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't need to call myGreatFunction with any arguments, you should be able to pass setTimeout a function reference:

setTimeout(myGreatFunction, 1000);

Also, you should always avoid passing setTimeout code that it needs to evaluate (which is what happens when you wrap the code in quotes). Instead, wrap the code in an anonymous function:

setTimeout(function() {
    // Code here...
}, 1000);

See the setTimeout page at the Mozilla Development Centre for more information.

Steve


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...