javascript - Call function once, then setInterval - Stack Overflow

I have a function that that I would like to call immediately, then use setInterval to update every ten

I have a function that that I would like to call immediately, then use setInterval to update every ten seconds.

Currently I am using something like

myFunction();
setInterval(function(){
 myFunction();
}, 10000);

Is there a better way to do this? I feel like there should be a way to tell setInterval to fire on call, but I cannot seem to find anything on it.

I have a function that that I would like to call immediately, then use setInterval to update every ten seconds.

Currently I am using something like

myFunction();
setInterval(function(){
 myFunction();
}, 10000);

Is there a better way to do this? I feel like there should be a way to tell setInterval to fire on call, but I cannot seem to find anything on it.

Share Improve this question edited Oct 7, 2013 at 20:09 Ian 50.9k13 gold badges104 silver badges111 bronze badges asked Oct 7, 2013 at 20:02 uberHasuuberHasu 1011 silver badge7 bronze badges 4
  • 6 If that function has no params, you can pass it in with setInterval(myFunc, 100000); other than that, looks fine. – tymeJV Commented Oct 7, 2013 at 20:04
  • 1 I've been using this language since 2007, and I think that's the only way to do it. That's just how setInterval works, really. – Joe Simmons Commented Oct 7, 2013 at 20:06
  • Wait, I just thought of something. I'll post an answer – Joe Simmons Commented Oct 7, 2013 at 20:09
  • Possible duplicate of Execute the setInterval function without delay the first time – asherbret Commented Oct 17, 2017 at 13:10
Add a ment  | 

3 Answers 3

Reset to default 5

This isn't any "better," but it does what you want with fewer lines:

myFunction();
setInterval(myFunction, 10000);

If you return the function from inside the function, you can use a little hack like this:

function foo() {
    alert('hi');
    return foo;
}

// no need to call it before setting the interval
window.setInterval( foo() , 3000 );

It executes immediately, and since the function returns itself, it keeps going.

jsFiddle example

Another way is to modify your function to call itself with setTimeout, then you can start the whole thing with a single line:

function myFunction() {
    // do stuff
    setTimeout(myFunction, 10000);
}
myFunction();

As pointed out in the ments, this is not exactly the same as using setInterval (which may drop some function calls depending on how long the code in the function takes to execute).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744177646a4561831.html

相关推荐

  • javascript - Call function once, then setInterval - Stack Overflow

    I have a function that that I would like to call immediately, then use setInterval to update every ten

    9天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信