Loop over array but with a time delay

2020-03-24 06:54发布

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.

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.

array

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

code

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

标签: javascript
3条回答
来,给爷笑一个
2楼-- · 2020-03-24 07:38

Use this function to make it easier to run:

function loopArr(arr, callback, time, infinite){
    console.log('loop run');
    var i=0,
        total=arr.length-1;
    var loop=function(){
            // RUN CODE
            console.log('loop arr['+i+']');
            callback( arr[i] );
            if (i < total ) {
                i++;
            } else { // LOOP END
                console.log('loop end!');
                if(!infinite) return;
                i=0 //restart
            }
            setTimeout( loop, time);
    }
    loop()
}

To use this function execute this:

loopArr(arr, callback, time, infinite)

Where:

  • arr is the array we need to loop, it could be a jQuery selector
  • callback is the executed function with one argument returned which is the selected item
  • time is the timeout needed for delay
  • infinite is set true or false if we need the code to repeat itself forever

Example using animate.css :

var imgShowHide = function(elm){
    var elm = $(elm); // select the item arr[i] via jQuery
    elm.css('animation-duration','2s').show()
        .addClass('animated bounceInRight')
        .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
            elm.removeClass('animated bounceInRight')
                .addClass('animated bounceInLeft')
                .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
                    elm.removeClass('animated bounceInLeft').hide()
                })
        });
}

// RUN
loopArr( $('#images > img'), imgShowHide, 4000, true);
查看更多
虎瘦雄心在
3楼-- · 2020-03-24 07:53

There's a really simple pattern for this type of iterator, using closure scope to store a loop counter and a nested looper() function which runs the setTimeout() iterator. The looper() function actually iterates the loop count, so there is no need for a for or do/while construct. I use this pattern often, and it works really well.

EDIT: Modified the condition to check for loop > 1, not loop > 0, which logged Loop count: 0. This can be tweaked, and technically, the looper() here runs 16 times.

(function(){
    var loop = 15;

    var looper = function(){
        console.log('Loop count: ' + loop);

        if (loop > 1) {
            loop--;
        } else {
            console.log('Loop end.');
            return;
        }

        setTimeout(looper, 15000);
    };

    looper();
})();

http://jsfiddle.net/userdude/NV7HU/2

查看更多
太酷不给撩
4楼-- · 2020-03-24 07:55
// 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);
    }
})();

Something like this?

查看更多
登录 后发表回答