开发者

Trigger anonymous function inside setInterval immediately

So I have a timer that looks like this

my_timer = setInterv开发者_高级运维al(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!


Use arguments.callee:

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


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;
});


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,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜