【问题标题】:Applying delay between iterations of javascript for loop在 javascript for 循环的迭代之间应用延迟
【发布时间】:2012-08-01 17:46:51
【问题描述】:

是否可以使用 jQuery 或下划线对 javascript for 循环的连续迭代应用延迟?我的页面上有一个 for 循环,用于在用户满足某些条件时弹出咆哮通知,如果有多个条件,我想错开咆哮通知而不是同时弹出多个。这是有问题的循环:

var badge_arr = response.split("Earned badge:");
//Start at 1 so I'm not getting everything before the first badge
for(i = 1; i < badge_arr.length; i++){
    responseStr += badge_arr[i];
    //Create growl notification
    //badge info echoed back will be of the form 
    //Earned badge: name: description: imgSource
    var badge_info = badge_arr[i].split(':');
    var title = 'NEW BADGE UNLOCKED';
    var text = 'You just unlocked the badge '+badge_info[0]+': '+badge_info[1];
    var img = badge_info[2];
    createGrowl(title, text, img);
} 

【问题讨论】:

  • 好吧,我正要接受另一个答案,然后才被删除。
  • @Xander 第一个元素立即为我执行,然后其余的同时执行。我看到它在你的 JSfiddle 中正常工作。我不知道这是怎么回事。但话又说回来,他不得不更改问题的参数,您的解决方案显然有效,至少对于警报。我只是假设我在实现它时犯了一个错误,放错了大括号之类的。

标签: javascript jquery for-loop delay underscore.js


【解决方案1】:
for(i = 1; i < badge_arr.length; i++){
    (function(i){
        setTimeout(function(){
            responseStr += badge_arr[i];
            //Create growl notification
            //badge info echoed back will be of the form 
            //Earned badge: name: description: imgSource
            var badge_info = badge_arr[i].split(':');
            var title = 'NEW BADGE UNLOCKED';
            var text = 'You just unlocked the badge '+badge_info[0] +
                       ': '+badge_info[1];
            var img = badge_info[2];
            createGrowl(title, text, img);
        }, 1000 * i);
    }(i));
}

插图:

for(i = 1; i <= 8; i++){
    (function(i){
        setTimeout(function(){
            document.body.innerHTML += i + "<br/>"
        }, 1000 * i);
    }(i));
} 

【讨论】:

  • 该死的正要指出您缺少* i 的错误-您在我可以之前对其进行了编辑...为此+1!
  • 你能解释一下为什么 * i 很重要吗?
  • @tim 如果你运行这个例子,它会变得更加明显。外循环递增i badge_arr.length 次。从而传递到内部闭包012 等...使setTimeout 每秒执行一次(1000 毫秒)。
  • @Xander,我在谷歌上寻找“延迟 for loop javascript”时发现了这一点。这个功能让我省去了很多烦恼,非常感谢!
  • 为什么我们不能有睡眠之类的东西?
【解决方案2】:

我更喜欢使用接收多次迭代的自调用函数:

(function loop(i) {          
   setTimeout(function () {   

      console.log('hello world'); // your code

      if (--i) loop(i); // iteration counter
   }, 5000) // delay
})(10); // iterations count 

【讨论】:

    猜你喜欢
    • 2017-04-03
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多