3

I created an array and inserted a setInterval in it, but tmp[0] doesn't work

tmp = new Array();
v = new Array();
for(i=0; i<2; i++){
j = 0;
tmp[i] = setInterval("if(j<10+(i*5)){alert(i+' '+j);j++;}else{clearInterval(tmp[i])}", 1000);
}
R. 久蔵
  • 187
  • 2
  • 5
  • 16

2 Answers2

5

Do Not use eval. Try this:

var tmp = new Array();
var v = new Array();
for (i = 0; i < 2; i++) {
    var j = 0;
    tmp[i] = setInterval(function () {
        if (j < 10 + (i * 5)) {
            alert(i + ' ' + j);
            j++;
        } else {
            clearInterval(tmp[i])
        }
    }, 1000);
}

Fiddle: http://jsfiddle.net/FKEL6/ (it is annoying with the popups, just so you are aware.)


This might do what you want it to do:

var tmp = new Array();
var v = new Array();
var i = 0;
for (i = 0; i < 2; i++) {
    createTmp(i);
}

function createTmp(p){
    var j = 0;
    tmp[p] = setInterval(function () {
        if (j < 10 + (p * 5)) {
            alert(p + ' ' + j);
            j++;
        } else {
            clearInterval(tmp[p])
        }
    }, 1000);
}
console.log(tmp);

Fiddle: http://jsfiddle.net/FKEL6/5/ (also has annoying alerts)

Naftali
  • 144,921
  • 39
  • 244
  • 303
0

The output of such a thing is:

2 0
2 1
2 2
2 3
2 4
2 5
...
2 18
2 19

etc, which is correct. It stops when j < 20.

But at the end your timer is still going on and all you are doing is calling clearInterval(tmp[2]) over and over, twice a second.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171