2

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.

Ian
  • 50,146
  • 13
  • 101
  • 111
uberHasu
  • 81
  • 1
  • 7
  • 6
    If that function has no params, you can pass it in with `setInterval(myFunc, 100000);` other than that, looks fine. – tymeJV Oct 07 '13 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 Oct 07 '13 at 20:06
  • Wait, I just thought of something. I'll post an answer – Joe Simmons Oct 07 '13 at 20:09
  • Possible duplicate of [Execute the setInterval function without delay the first time](https://stackoverflow.com/questions/6685396/execute-the-setinterval-function-without-delay-the-first-time) – asherbret Oct 17 '17 at 13:10

3 Answers3

4

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

myFunction();
setInterval(myFunction, 10000);
Bucket
  • 7,415
  • 9
  • 35
  • 45
2

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

Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
  • 1
    Pretty cool idea. Let's hope there's no exceptions before the `return`, otherwise it won't act like the OP's original code – Ian Oct 07 '13 at 20:17
  • 2
    This hurts my eyes. It's almost as bad as `setInterval((foo(), foo), 3000)` which [works too](http://jsfiddle.net/47Df8/), but is so hard to read… – user123444555621 Oct 07 '13 at 20:19
  • I agree. It's basically the only way to do what he asked for, though. – Joe Simmons Oct 07 '13 at 20:24
1

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 comments, 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).

bfavaretto
  • 71,580
  • 16
  • 111
  • 150