Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval with self-executing function

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?

like image 750
Afshin Mehrabani Avatar asked Apr 27 '26 06:04

Afshin Mehrabani


2 Answers

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);
like image 198
jAndy Avatar answered Apr 28 '26 19:04

jAndy


Set interval requires the function reference, not the undefined returned from the function. Just remove the '()' at the end of the anonymous function.

like image 42
jhummel Avatar answered Apr 28 '26 21:04

jhummel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!