Javascript 带循环时间的 setInterval
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8421998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setInterval with loop time
提问by bingjie2680
setInterval(function(){}, 200)
this code run the function each 200 miliseconds, how do I do it if I only want the function to be ran 10 times.
这段代码每 200 毫秒运行一次该函数,如果我只希望该函数运行 10 次,我该怎么做。
thanks for help.
感谢帮助。
回答by karim79
Use a counter which increments each time the callback gets executed, and when it reaches your desired number of executions, use clearInterval()
to kill the timer:
使用每次执行回调时递增的计数器,当它达到您想要的执行次数时,使用clearInterval()
终止计时器:
var counter = 0;
var i = setInterval(function(){
// do your thing
counter++;
if(counter === 10) {
clearInterval(i);
}
}, 200);
回答by Esailija
(function(){
var i = 10;
(function k(){
// your code here
if( --i ) {
setTimeout( k, 200 );
}
})()
})()
回答by shadownrun
if you want it to run for 10 times and the time it should run is every 200 miliseconds then 200X10 = 2000
如果你想让它运行 10 次并且它应该运行的时间是每 200 毫秒那么 200X10 = 2000
var interval = setInterval(yourfunction, 200);
setTimeout(function() {
clearInterval(interval)
}, 2000);
but it only runs 9 times so we must add more 200 miliseconds
但它只运行了 9 次所以我们必须增加 200 毫秒
var interval = setInterval(yourfunction, 200);
setTimeout(function() {
clearInterval(interval)
}, 2200);
or you could run it before the setInterval
或者你可以在 setInterval 之前运行它
yourfunction();
var interval = setInterval(yourfunction, 200);
setTimeout(function() {
clearInterval(interval)
}, 2000);
回答by JavaScripter199
Just use a for loop instead, much easier:
只需使用 for 循环,更容易:
Just try this code.
试试这个代码。
for (counter=0; counter<0; counter++) {}