0

I'm attempting to launch severals setInterval functions "at once". I've got a for loop which call a function indexed, which contains the setInterval.

I've looked for answer both here: JavaScript closure inside loops – simple practical example and here: setInterval with loop time

but i'm still struggling with no success...

I've checked tab and tab2, both works if I read them with console.log outside of the setInterval function

here is my code :

var tab = <?php echo json_encode($matrice); ?>;
var tab2 = new Array();

var funcs = [];

var countDownAction = new Array();

function countDown(i)
{
    countDownAction[i] = setInterval(function(i)
    {
        // some actions

    }, 1000);  
}


for(var i = 0; i < tab.length; i++)
{
    tab2[i] = [];

    tab2[i]['hours'] = tab[i]['hours'];
    tab2[i]['minutes'] = tab[i]['minutes'];
    tab2[i]['seconds'] = tab[i]['seconds'];

    funcs[i] = countDown.bind(this, i);
}

for(var j = 0; j < tab.length; j++)
{
    funcs[j]();
}
Community
  • 1
  • 1
gZ Fab
  • 91
  • 1
  • 11

3 Answers3

2

The function inside setInterval is called without any arguments. Thus, i inside the function's body will be undefined.

Consider rewriting countDown function as follows:

function countDown(i)
{
    countDownAction[i] = setInterval(function()
    {
        // some actions

    }, 1000);  
}

This way, the body of the function has access to i in the outer scope.

To clear the timers, say 3.5 seconds later, you can do the following:

setTimeout(function () {
    for (var k = 0; k < tab.length; k++) {
        clearInterval(countDownAction[k]);
    }
}, 3500);
Adeel Zafar Soomro
  • 1,492
  • 9
  • 15
  • it may sounds stupid, but I'm not able to clear those multiples setInterval with a function called the same way I've called those setInterval functions... – gZ Fab May 25 '16 at 18:43
0

I recommend you use global variable for countDownAction , can you try the following instead.

window.countDownAction = window.countDownAction || [];
Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76
0

the problem is that the loop is so fast , so the setInterval function get the last value of i variable. we need to set i value directly in the interval by using external function like this :

var interval_Array = new Array();

for(var i; i<= number ;i++){
    var newinterval = (i+1) * 1000; //Place any process according to your time
    external_function(i,newinterval);
};

function external_function(this_i,this_interval){
    interval_Array[i]=setInterval(function(){
      //your script that contains i variable
    },this_interval);
};