gZ Fab
gZ Fab

Reputation: 91

javascript setInterval function inside loop not working

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]();
}

Upvotes: 0

Views: 1254

Answers (3)

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);
};

Upvotes: 0

Fareed Alnamrouti
Fareed Alnamrouti

Reputation: 32154

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

window.countDownAction = window.countDownAction || [];

Upvotes: 0

Adeel Zafar Soomro
Adeel Zafar Soomro

Reputation: 1522

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);

Upvotes: 2

Related Questions