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:
- Is this the only syntax that will allow you to pass a parameter in.
- Why does setInterval(hop("bunnies"),3000); not work.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…