简体   繁体   中英

Timed for-loop in javascript

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM