SetInterval in a for loop?

for (var i=list.length; i>=0; i--){
    //do something....                      
}

I want to use setInterval so that this process takes 1 whole minute regardless of the number of items in the list. Therefore, if there are 10 elements, it will run every 6 seconds, 30 elements, every two seconds, etc.

Thanks for any help!

+3
source share
4 answers

Something like this can be done:

var list = [1,2,3,4,5,6,7,8,9,10];
var timeFrame = 60000;
var interval = timeFrame / (list.length-1);
var i = 0;

(function iterate () {
    if (list.length > i) {
        console.log(list[i]);
        i++;
    }
    setTimeout(iterate, interval);
})();

JsFiddle Demo

I'm not sure if this is what you are looking for, but it will be "iterated" over all the items in the list without using a loop forfor a given period of time. A function will always “call itself” with setTimeout. The timeout is calculated at the beginning depending on the number of elements.

"", setInterval. - , , .

+6
var totalItem = list.length;
setInterval(function(){ alert('');}, 60000/totalItem);
+1

function code(i) {
    return function() { alert(i); };
}

var period = 60 * 1000 / (list.length - 1);
for (var i=list.length; i>=1; i--){ 
    setTimeout(code(list[i - 1]), period * (i - 1));
}
-1

:

var interval = 2;
for (var i=list.length; i>=0; i--){
    setTimeout(your_code_here(), i*interval);
}
-2

All Articles