-->

How can I do loop to a setInterval? (with array) -

2019-09-01 05:05发布

问题:

In my code I'm trying to draw a rectangle at a time with help of a Matter.js plugin. The effect that I want, and I have is this: http://gyazo.com/0b84f082c4518c7c42a1651173e7b961 I'm getting from database how many rectangles should draw ( in variable entradas[] ). But I have many positions in array, which one says how many rectangles should draw. With timer "desenha" I draw one rectangle by one, up to entradas[].

My problem is that I can't make the loop for, when it draws all the rectangles from the first row, it draw the next rectangles from the second row, and so on.. For now it only draws the rectangles from first row.

That's the part of the code where I try to do it:

var li=1;
desenha=setInterval(
     function() {

           if(categoria[li]){
             entra=entradas[li];
             tex=texturas[li];
           }

           if(rects<entradas[li]){
                World.add(_world,
                    Bodies.rectangle( Math.round(Common.random(300,400)),-20,Math.round(Common.random(20,30)),Math.round(Common.random(20,30)), {
                        render: {
                         strokeStyle: '#ffffff',
                         sprite: {
                            texture: tex
                         }
                        }
                    })

            );  
            }
          }
            , 500);

contagem=setInterval( function(){
        if(rects<entradas[li]){
            rects=rects+1;

            document.getElementById("mytext").value = rects;
            rectsmoney=rects*valor[1];
            document.getElementById("mytext2").value = Math.round(rectsmoney);

       } 
       },500);

if(rects>=entradas[li]){
    rects=0;
    li++;
}

With help of an echo I know that it prints every row to entradas[];

Anyone can help me to make this loop works?

回答1:

Wrap the setInterval functions and give them a temporary scope.. As desenha is a global variable, it will reassign desenha when looping. A better way is to keep a global array to store intervals.

(function(li) { desenha[li] =setInterval(
     function() {

           if(categoria[li]){
             entra=entradas[li];
             tex=texturas[li];
           }

           if(rects<entradas[li]){
                World.add(_world,
                    Bodies.rectangle( Math.round(Common.random(300,400)),-20,Math.round(Common.random(20,30)),Math.round(Common.random(20,30)), {
                        render: {
                         strokeStyle: '#ffffff',
                         sprite: {
                            texture: tex
                         }
                        }
                    })

            );  
            }
          }
            , 500);
         })(li);