Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger anonymous function inside setInterval immediately

So I have a timer that looks like this

my_timer = setInterval(function(){
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}, 1000);

And I want it to run immediately, and every second after that. I tried appending () to the end of the function, but that caused it to run only once (because it is not returning the function itself to the setInterval?). I then tried to return this; so that it would possibly return the function itself, but that did no good either. That was a random guess.

Is there any way I can get this to work without creating a named function? Thanks!

like image 945
Shane Reustle Avatar asked Jun 26 '26 07:06

Shane Reustle


1 Answers

Use arguments.callee:

my_timer = setInterval((function(){     
    do_something_amazing();     
    do_more.stuff_here();     
    var etc_etc = "foo" + bar;
    return arguments.callee; 
})(), 1000); 
like image 127
Shurdoof Avatar answered Jun 28 '26 19:06

Shurdoof



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!