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);
}
3
  • 3
    What did you expect to happen? Commented Aug 30, 2011 at 13:12
  • It should alert: "0 0" "1 0" "0 1" "1 1" "0 2" "1 2" ... Commented Aug 30, 2011 at 13:18
  • @キューゾ リファイ see the update to my answer.. Commented Aug 30, 2011 at 13:26

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

8 Comments

OP isn't using eval, they're using the deprecated form of setInterval by passing a string.
@キューゾ リファイ what does that mean it doesnt run? what do you want it to do?
Using a function creates another problem: scope.
@キューゾ リファイ i will always be 2 because it is a global variable... and you increased it in the loop.
@キューゾ リファイ I believe this might do what you want it to do: jsfiddle.net/FKEL6/5
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.