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

JavaScript: run setInterval at page load - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Nov 7, 2012 at 17:15 David Hellsing 109k44 gold badges180 silver badges214 bronze badges asked Nov 7, 2012 at 16:52 chadohchadoh 4,4326 gold badges42 silver badges65 bronze badges 5
  • 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
Add a ment  | 

2 Answers 2

Reset to default 6

How about:

setInterval(​function foo(){
    // logic
    return foo;
}(), 20000);​
(function wrap(){
    myFunction();
    setTimeout( wrap, 20000 );
})();
发布评论

评论列表(0)

  1. 暂无评论