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
?
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
?
- Your example is flawed, you are calling the function instead of assigning it. – epascarello Commented Nov 7, 2012 at 16:55
- This question is a duplicate of stackoverflow./questions/6685396/… .. I've also flaged it – Mihai Matei Commented Nov 7, 2012 at 16:55
- 2 I would go with first calling the function and then scheduling it for the sake of simplicity and maintainability. – AlexStack Commented Nov 7, 2012 at 16:58
- @MateiMihai This is definitely a dup. What's it mean that you flagged it? Can I shut this whole thing down and just refer everyone to the other, older question? – chadoh Commented Nov 9, 2012 at 1:56
- @AlexStack It's a good approach. My actual code was a teeny bit more plex, so it seemed easier if I wouldn't have to do that. But it was my approach until I heard back from the munity on if there is a better way. It doesn't really seem like it. – chadoh Commented Nov 9, 2012 at 1:57
2 Answers
Reset to default 6How about:
setInterval(function foo(){
// logic
return foo;
}(), 20000);
(function wrap(){
myFunction();
setTimeout( wrap, 20000 );
})();