每五秒钟使用Javascript循环一次 [英] Loop every five seconds in Javascript
本文介绍了每五秒钟使用Javascript循环一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在JS(或JQuery)中编写一个简单的循环,该循环每五秒钟更新一次图像,总共更新15秒(因此三个循环),然后退出.
I'm trying to write a simple loop in JS (or JQuery) that updates an image every five seconds, for a total of 15 seconds (so three loops), and then quits.
它应该像这样:
- 等待五秒钟
- 执行
- 等待五秒钟
- 执行
- 等待五秒钟
- 执行
- 退出
但是setTimeout
似乎只能工作一次.
But setTimeout
only seems to work once.
作为测试,我已经尝试过:
As a test, I've tried:
function doSetTimeout(i) {
setTimeout(function() { alert(i); }, 5000);
}
for (var i = 1; i <= 5; ++i)
doSetTimeout(i);
不起作用: http://jsfiddle.net/ubruksco/
我也尝试过:
for(var i = 1; i <= 5; i++) {
(function(index) {
setTimeout(function() { alert(index); }, 5000);
})(i);
}
不起作用: http://jsfiddle.net/Ljr9fq88/
推荐答案
var time = 1;
var interval = setInterval(function() {
if (time <= 3) {
alert(time);
time++;
}
else {
clearInterval(interval);
}
}, 5000);
您只需创建一个间隔并在第三次之后杀死它
you can simply create an interval and kill it after the 3rd time
这篇关于每五秒钟使用Javascript循环一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文