0

I want to trigger my for-loop every 2 seconds. My code works but makes three ball objects at once instead of making one ball every 2 seconds 3 three times in a row.

Here's my for-loop, this is just a part of my code.

for (i=0;i<3;i++) {
    ball= {
        x : canvas.width,
        y : Math.random()*canvas.height,
        speedX : -130,
        speedY : 0,
        radius : 10,
        color : "red"           
    };
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
HeadachePanda
  • 175
  • 1
  • 12

1 Answers1

4

This will create a new ball three times, one every 2 seconds. To create more simply change the 3 in the for loop and more will be created, 1 every 2 seconds.

function CreateBall(){
    ball = {
        x : canvas.width,
        y : Math.random()*canvas.height,
        speedX : -130,
        speedY : 0,
        radius : 10,
        color : "red",
    };
}
for (i=0;i<3;i++) setTimeout(CreateBall, i*2000);
Hunter Larco
  • 785
  • 5
  • 17