8

是否可以使用 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);
} 
4

2 回答 2

31
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));
} 

于 2012-08-01T17:50:04.690 回答
4

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

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

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

      if (--i) loop(i); // iteration counter
   }, 5000) // delay
})(10); // iterations count 
于 2016-01-29T23:43:08.233 回答