Using setInterval
, array.push()
, for loops, I want one bubble to appear every 3 seconds until the length of the array bubbles becomes 10.
However, when I execute my code, 10 bubbles appear altogether at once, and console.log(array.length)
shows that the length is growing, although I set it to be smaller than 10.
I think there is something wrong with how I arrange the codes, can anyone help?
let bubbles = [];
var n = 10;
function setup() {
createCanvas(600, 400);
}
function addBubbles() {
for (let i = 0; i < n; i++) {
let x = random(50, 550);
let y = random(50, 350);
let r = random(10, 50);
let b = new Bubble(x, y, r);
setInterval(bubbles.push(b), 3000);
}
}
function draw() {
background(0);
addBubbles();
for (let i = 0; i < n; i++) {
bubbles[i].show();
bubbles[i].move();
}
}
class Bubble {
constructor(_x, _y, _r, _c) {
this.x = _x;
this.y = _y;
this.r = _r;
this.c = _c;
}
move() {
this.x = this.x + random(-5, 5);
this.y = this.y + random(-5, 5);
}
show() {
stroke(255);
noFill();
strokeWeight(4);
ellipse(this.x, this.y, this.r * 2);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>