Applying delay between iterations of javascript fo

2019-01-24 13:42发布

问题:

Is it possible to apply a delay to successive iterations of a javascript for-loop using jQuery or underscore? I have a for-loop on my page that I am using to pop up growl notifications when users fulfill certain conditions and if there are multiple conditions I would like to stagger the growl notifications instead of popping up several at the same time. Here is the loop in question:

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

回答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));
}

EXAMPLE



回答2:

I prefer to use self-invoking function that receives a number of iterations:

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

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

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