I'll like to make some elements in an array appear at different times, the time will be decreasing over time (so the elements will appear faster and faster). I had tried with setTimeout and setInterval with no luck, I think it is because I'm looping through the array.
You cannot achieve that via intervals. Yet, it's possible with recursive timeouts. For example, let's say that the time is decreasing by 2x:
const initialDuration = 10000;
function someAnimation(duration) {
// Your animation code here...
setTimeout(() => someAnimation(duration / 2), duration);
}
someAnimation(initialDuration);
Here's a simple p5.js example that should hopefully point you in the right direction.
I'm calling the setTimeout function for every object on initialisation. The delay of the timeout is incremented by a value incrementor which decreases each iteration.
let circles = [];
let count = 100;
let incrementor = 500;
let delay = 500;
function setup() {
createCanvas(400, 400);
for (let i = 0; i < count; i++) {
let circle = {
x: random(width),
y: random(height),
show: false,
}
incrementor *= 0.9;
delay += incrementor;
setTimeout(() => circle.show = true, delay);
circles.push(circle);
}
}
function draw() {
background(220);
noStroke()
fill(0, 128, 128);
for (let circle of circles) {
if (circle.show) {
ellipse(circle.x, circle.y, 10, 10);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>