javascript setInterval in array
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{开发者_Go百科clearInterval(tmp[i])}", 1000);
}
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)
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.
精彩评论