admin管理员组文章数量:1399225
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
3 Answers
Reset to default 5This 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).
本文标签: javascriptCall function oncethen setIntervalStack Overflow
版权声明:本文标题:javascript - Call function once, then setInterval - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744177646a2594077.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论