javascript - 运行函数 x 次

标签 javascript jquery

我试图让一个 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/

相关文章:

javascript - 如何在 jquery 中引用 ImageButton?

javascript - 如何保留 html 内容历史记录以使后退按钮起作用?

javascript - 一段时间后如何加载javascript?

javascript - json对象访问数据

javascript - 检索搜索结果中两个最大的评分

javascript - 在 html5 中使用网络摄像头拍摄单张照片

php - Ajax 和 PHP : MySQL Query Not Fetching Any Rows

javascript - 获取数组 VueJS 的最后一项

javascript - 在 Google map 信息窗口中加载动画

jquery - 这段代码是什么意思? (jquery)