2

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.

Sanjith
  • 289
  • 1
  • 3
  • 8
  • @Rajesh thanks for your comment. But I want to execute the codes inside the setInterval method, before the further increment of i value in the for loop. – Sanjith Dec 02 '16 at 07:30
  • apologies for my misunderstanding. – Rajesh Dec 02 '16 at 07:45
  • This might help: http://stackoverflow.com/questions/13583280/javascript-execute-async-function-one-by-one – Rajesh Dec 02 '16 at 07:48

3 Answers3

2

Use closure inside for loop:

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

hope this solves your problem

Rajesh
  • 24,354
  • 5
  • 48
  • 79
pareshm
  • 4,874
  • 5
  • 35
  • 53
  • It helps me a lot. But I want to maintain the same 'i' value until calling clearInterval() method. Is it possible? – Sanjith Dec 02 '16 at 09:36
0

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);
};
ixpl0
  • 748
  • 5
  • 15
0

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()
Rajesh
  • 24,354
  • 5
  • 48
  • 79