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"           
    };
}
2
  • Where is the part of your code that does the timer? Commented Apr 24, 2014 at 13:00
  • I didn't yet had a timer part because I wasn't quite sure how to code this part. I was hoping someone would show me how it was done in an answer. Commented Apr 25, 2014 at 13:02

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

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.