admin管理员组文章数量:1356914
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);
}
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);
}
Share
Improve this question
asked Aug 30, 2011 at 13:10
R. 久蔵R. 久蔵
1873 gold badges5 silver badges16 bronze badges
3
- 3 What did you expect to happen? – Blazemonger Commented Aug 30, 2011 at 13:12
- It should alert: "0 0" "1 0" "0 1" "1 1" "0 2" "1 2" ... – R. 久蔵 Commented Aug 30, 2011 at 13:18
- @キューゾ リファイ see the update to my answer.. – Naftali Commented Aug 30, 2011 at 13:26
2 Answers
Reset to default 5Do 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/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/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.
本文标签: javascript setInterval in arrayStack Overflow
版权声明:本文标题:javascript setInterval in array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744023521a2577640.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论