Rich
Rich

Reputation: 5731

Get setInterval to perform an action a certain amount of times based on array

I am trying to iterate through values in an array, via a setInterval(), every 10ms.

However because the computer cannot process the iterations that fast, my clearInterval() is in fact clearing the interval before the array has been fully iterated through.

The below is just an example of what I am doing, NOT the actual code which is more CPU intensive.

How do I fix the code so that it will iterate all the to the end, regardless of CPU performance?

var blah = ['a','b','c'];
i=0;

int = setInterval(function(){   
    console.log(blah[i]);
    i++;
},10);

timeout = setTimeout(function(){
    clearInterval(int);
}, blah.length * 10);

Upvotes: 0

Views: 127

Answers (4)

Akshay
Akshay

Reputation: 3198

I personally wouldn't want to use setInterval for what you are trying to do. If your aim is to throttle the process, meaning having only one iteration being processed at a given time, and adding a delay before the next process interation, 'setInterval' cannot enforce that. It can only ensure each process iteration is started at a fixed interval.

This is how I would do it:

<script>

var items = [1, 2, 3, 4, 5];

function processOffersOneAtATime() {
    if (items.length != 0) {
        var item = items.pop();
        setTimeout(function() {
         console.log(item);
         //do time consuming cpu intensive operation here
         processOffersOneAtATime();
        }, 1000);
    }
}
//kick start the process
 processOffersOneAtATime();
 </script>

Upvotes: 0

NilsH
NilsH

Reputation: 13821

I would solve it like this:

var blah = ['a','b','c'];

function iterate(index) {
    console.log(blah[index]);
    if(index < blah.length - 1) {
        setTimeout(function() {iterate(++index)}, 10);
    }
}

iterate(0);

Then you wouldn't have to deal with clearing the timeout, and you have also no global index variable with closure capture issues.

Upvotes: 0

Py.
Py.

Reputation: 3599

I'd go with something along the lines of

var inter, 
    blah = ['a','b','c','d','e'],
    i=0;
inter = setInterval(function(){   
    console.log(blah[i]);
    i++;
    if (i === blah.length) {
        clearInterval(inter);
    }
},1);

P.S: I put one ms cause 10ms worked just fine for me.

Upvotes: 1

rahul maindargi
rahul maindargi

Reputation: 5655

Use this

var blah = ['a','b','c'];
var i=0;

var intervalId = setInterval(function(){   
    console.log(blah[i]);
    i++;
    if(i==blah.length){ // i== 3 all array elements processed. then clear interval
      clearInterval(intervalId );
    }
},10);

Working example http://jsfiddle.net/B8ya3/

Upvotes: 2

Related Questions