遍历数组但有时间延迟 [英] Loop over array but with a time delay

查看:49
本文介绍了遍历数组但有时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历数组.但是,我想在每个数组值之间添加15秒的延迟.这会将值1写入控制台,然后倒计时15秒,然后将值2写入控制台,依此类推.

I am trying to loop over an array. However, I would like to add a 15 second delay between each array value. This will write value 1 to console, then count down 15 seconds and write value 2 to console, and so on.

我不确定该怎么做.到目前为止,我的代码仅一次在控制台上将数字15一直输出到1,没有实际的递减计数,也没有数组值.

I'm not sure exactly how to do this. My code as of now just outputs the numbers 15 all the way to 1 on the console at once with no actual count down and no array values.

数组

["l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11", "l12", "l13", "l14", "l15", "l16"] 

代码

var adArray = [];
// get links with class adfu
var adfuClass = document.getElementsByClassName('adfu');
for (var i = 0; i < adfuClass.length; i++) {
    var ids = adfuClass[i].id
    var newIds = ids.replace(/tg_/i, "l");
    adArray.push(newIds);
}
// get links with class ad30
var ad30Class = document.getElementsByClassName('ad30');
for (var i = 0; i < ad30Class.length; i++) {
    var ids = ad30Class[i].id;
     var newIds = ids.replace(/tg_/i, "l");
     adArray.push(newIds);
}
// get links with class adf
var adfClass = document.getElementsByClassName('adf');
for (var i = 0; i < adfClass.length; i++) {
    var ids = adfClass[i].id;
     var newIds = ids.replace(/tg_/i, "l");
     adArray.push(newIds);
}
// loop through array with all new ids
for (var i = 0, l = adArray.length; i < l; i++) {
    var counter = 15;
    var countDown = setTimeout(function() {
        console.log(counter);
        if (counter == 0) {
            console.log(adArray[i]);
        }
        counter--;
    }, 1000);
}

推荐答案

// loop through array with all new ids
var i = 0, l = adArray.length;
(function iterator() {
    console.log(adArray[i]);

    if(++i<l) {
        setTimeout(iterator, 15000);
    }
})();

像这样吗?

这篇关于遍历数组但有时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆