Sanjith
Sanjith

Reputation: 319

How to use setInterval() inside for loop

Please find my code below.

for (i= 0; i < region.length; i++) {
                    point = region[i];
                    animation = setInterval(function () {
                     ..........
                    }, 12);
                }

I want to execute the codes in setInterval before i value changes from 0 to 1. But currently after all the execution of for loop only, codes in the setInterval method is getting executed. is there any way to achieve my requirement.

Upvotes: 2

Views: 4714

Answers (3)

pareshm
pareshm

Reputation: 4984

Use closure inside for loop:

(function(i) {
  setInterval(function() {
    console.log("inside setinterval" + i)
  }, 10);
})(i)

hope this solves your problem

Upvotes: 2

Rajesh
Rajesh

Reputation: 24925

You should use recursion for such requirements. Also, you should use setTimeout as setInterval will run for eternity(till page exists) until you clear it.

var i = 0;
var MAX_COUNT = 10;
function doSomething(str){
  console.log(str);
  processData();
}

function initSetTimeout(callback){
  setTimeout(callback, 1000)
}

function processData(){
  if(++i<MAX_COUNT)
    initSetTimeout(doSomething.bind(null, i))
}
processData()

Upvotes: 0

ixpl0
ixpl0

Reputation: 756

Async loop you need:

var len = region.length;
var i = 0;
var animate = function(){
    setTimeout(function () {
        point = region[i];
        //do something..........
        if (i++ < len) animate();
    }, 12);
};

Upvotes: 0

Related Questions