问题
I want to run my function at the first time immediately (without timeout) so I do this:
setInterval(function(){
alert("Boo");
}(), 1000);
The function executed at first time but in next intervals, nothing happened. Why?
回答1:
The better question is, what are you actually trying to achieve ?
You don't return
anything from the self-invoking function, so it will return the undefined
value implicitly, which is passed over to setTimeout
. After the initial call, the line would look like
setInterval(undefined, 1000);
which obviously, makes no sense and won't continue calling anything.
You either need to to return
another function from your self-invoking function, or just don't use a self-invoking function and just pass over the function reference.
Update:
You updated your question. If you want to run a function "once" on init and after that use it for the interval, you could do something like
setInterval((function() {
function loop() {
alert('Boo');
};
loop();
return loop;
}()), 1000);
回答2:
Set interval requires the function reference, not the undefined returned from the function. Just remove the '()' at the end of the anonymous function.
回答3:
It's because it is invoked, not passed. If you want an immediate invocation, just give it a name, and return it.
setInterval(function foo() {
alert("boo");
return foo;
}(), 1000);
This is called a named function expression. You should be aware that in most browsers the foo
identifier will only be available inside foo
, but older IE has issues that causes the identifier to leak to the outer scope.
This is usually not an issue, but you should be aware of it when choosing the function name.
回答4:
Because what setInterval
"sees" is the return of your self-executing function - undefined
.
Try this instead:
setInterval(function()
{
alert("Boo");
return arguments.callee;
}(), 1000);
Note:
As I Hate Lazy pointed out arguments.callee
isn't permitted in Strict Mode.
回答5:
Here's what I've done in the past as my approach:
(function loop () {
// do stuff
window.setTimeout(loop, 1000);
})();
回答6:
You self executing function does not return a function to use as argument of setInterval
, so it shows alert before the call to setInterval
and than setInterval
is essentially no-op.
You can see Firefox complaining about empty call to setInterval
if you want.
回答7:
You could write it like this:
setInterval((function() {
function boo() {
alert("boo");
};
boo();
return boo;
})(), 1000);
But I'd suggest that you declare the function outside of the interval.
来源:https://stackoverflow.com/questions/13771889/setinterval-with-self-executing-function