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
217 views
in Technique[技术] by (71.8m points)

javascript - setInterval using a non anonymous function requiring parameters has to be inside an anonymous function. Why?

Ok I have reviewed several postings here and elsewhere regarding setInterval in jquery/javascript the annoying thing about the answers is that I am not learning why the solutions work.

Please consider:

Using an anonymous function we can set an alert to repeatedly output "bunnies":

setInterval(function(){
  alert("bunnies")
},3000);

But if we want to use a non anonymous function we have to code

setInterval(hop,3000);

where funct:

function hop(){
    alert("bunnies");
}

If we attempt to code:

setInterval(hop(),3000);

hop is executed but once only. I do not understand why this is. I have read various SO's on this which imply that we need to be passing a reference to setInterval. Does this imply that the first form setInterval(hop,3000); passes by reference. If so could this be explained?

Therefore we have an issue. In that obviously it would be desireable to be able to pass a parameter to function hop like .....

setInterval(hop("bunnies"),3000);

where funct:

function hop(msg){
    alert(msg);
}

This does cause hop to be invoked and "bunnies" to be output but again the function is invoked once only.

So as far as I can work out the only way to pass a parameter to a function being controlled by setInterval is to incorporate it inside an anonymous function:

setInterval(function(){
 hop("bunnies")
},3000);

this passes the parameter and repeats the execution of hop alerting us to bunnies every 3 seconds (very important to be alert to bunnies).

Questions therefore:

  1. Is this the only syntax that will allow you to pass a parameter in.
  2. Why does setInterval(hop("bunnies"),3000); not work.
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

setInterval expects a function as the first parameter. When you attempt:

setInterval(function() {...}, 100);

or

setInterval(funcName, 100);

you are correctly passing a function.

Whereas, when you attempt setInterval(funcName(), 100);, you are actually calling the function and passing its return value to setInterval which is incorrect.


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

...