在 javascript for 循环的迭代之间应用延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11764714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:16:30  来源:igfitidea点击:

Applying delay between iterations of javascript for loop

javascriptjqueryfor-loopdelayunderscore.js

提问by jaimerump

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:

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

回答by xandercoded

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

例子

回答by Andrei

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

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

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

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

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