我试图让一个 div 每 30 秒出现一次,但只出现 5 次。我的代码工作正常,只是循环 divs 并每 30 秒显示一个 div,但我需要它在完成 5 次后停止。
$(window).bind("load", function flashing() {
var counter = 0,
divs = $('.flash-image');
function showDiv () {
divs.hide() // hide all divs
.filter(function (index) { return index == counter % 30; })
.show('fast');
counter++;
};
showDiv(); // show first div
setInterval(function () {
showDiv(); // show next div
}, 1 * 1000); // do this every 1 seconds
});
最佳答案
var amount = 0;
var timerId = setInterval(function () {
showDiv(); // show next div
amount++;
if(amount === 5) {
clearInterval(timerId);
}
}, 1 * 1000); // do this every 1 seconds
关于javascript - 运行函数 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348300/