Вопрос

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"           
    };
}
Это было полезно?

Решение

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top