申请的JavaScript循环迭代之间的延迟(Applying delay between iter

2019-06-26 16:25发布

是否有可能申请的延迟,为循环使用jQuery或下划线一个JavaScript的连续迭代? 我有我的网页上一个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);
} 

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



Answer 2:

我更喜欢使用接收多次迭代的自我呼叫功能:

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

      alert('hello world'); // your code

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


文章来源: Applying delay between iterations of javascript for loop