最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger anonymous function inside setInterval immediately - Stack Overflow

programmeradmin6浏览0评论

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!

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!

Share Improve this question asked Dec 20, 2010 at 19:17 Shane ReustleShane Reustle 8,9528 gold badges43 silver badges52 bronze badges 2
  • About appending (): indeed, you're setting the returned value as a parameter, not a reference to the function. BTW, why don't you want to create a named function? – Marcel Korpel Commented Dec 20, 2010 at 19:19
  • No reason really, I was just hoping to learn some fancy new trick to call an anonymous function immediately, while having it return itself. – Shane Reustle Commented Dec 20, 2010 at 19:26
Add a ment  | 

3 Answers 3

Reset to default 5

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)

  1. 暂无评论