运行函数x次数

时间:2013-06-27 16:20:30

标签: javascript jquery

我试图让div每30秒出现一次,但只有5次。我的代码工作得很好,只是循环通过div并每隔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 
});

2 个答案:

答案 0 :(得分:3)

var amount = 0;
var timerId = setInterval(function () {
    showDiv(); // show next div
    amount++;
    if(amount === 5) {
        clearInterval(timerId);
    }
}, 1 * 1000); // do this every 1 seconds 

答案 1 :(得分:0)

 $(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    
    var inter = setInterval(function () {
        if(counter < 5){
          showDiv(); // show next div
        }else{
          clearInterval(inter);
        }
    }, 1 * 1000); // do this every 1 seconds 
});