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?
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);
Set interval requires the function reference, not the undefined returned from the function. Just remove the '()' at the end of the anonymous function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With