chadoh
chadoh

Reputation: 4432

JavaScript: run setInterval at page load

I want to run a bit of code every 20 seconds. That works fine. But I'd like setInterval to be run when first encountered, and then to start timing (instead of doing the timing first).

Obviously, I can do something like:

myFunction();
setInterval(myFunction, 20000);

But I find that a little inelegant. I'd prefer to do something like

setInterval(myFunction, 20000, { waitBeforeFirstRun: false });

Does such a setting exist for setInterval?

Upvotes: 2

Views: 4330

Answers (2)

David Hellsing
David Hellsing

Reputation: 108472

How about:

setInterval(​function foo(){
    // logic
    return foo;
}(), 20000);​

Upvotes: 6

Esailija
Esailija

Reputation: 140210

(function wrap(){
    myFunction();
    setTimeout( wrap, 20000 );
})();

Upvotes: 5

Related Questions