Shane Reustle
Shane Reustle

Reputation: 8952

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!

Upvotes: 2

Views: 1544

Answers (3)

Emmett
Emmett

Reputation: 14327

This doesn't technically create any named functions, but I'm not sure why you'd want to do it:

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

Upvotes: 3

Shurdoof
Shurdoof

Reputation: 1719

Use arguments.callee:

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

Upvotes: 5

Marvin Smit
Marvin Smit

Reputation: 4108

Would this work for you?

function startItUp()
{
   bla();
   setInterval( bla, 1000);
}

function bla()
{
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}

Hope this helps,

Upvotes: 2

Related Questions