'Way of setting the duration of a particle spawner loop help and way of stopping the function loop
I am using Pixi.js to spawn some particles on a canvas, but I need the particles to be spawning only for some time (3 seconds).
I created a loop function that spawns the particles, but I don't know how to end it from spawning after some time:
var particles = [];
function spawnFountain(){
var particle = new PIXI.Sprite.from('./Assets/particle.png');
app.stage.addChild(particle);
particles.push(particle);
setTimeout( () => {
spawnFountain();
},10)
}
I need this function to stop spawning after 3 seconds.
Solution 1:[1]
var particles = [];
function spawnFountain(){
var particle = new PIXI.Sprite.from('./Assets/particle.png');
app.stage.addChild(particle);
particles.push(particle);
}
var intervalStart = new Date();
var interval = setInterval(() => {
var now = new Date();
if (now - intervalStart > 3000) { // 3 seconds
clearInterval(interval);
return;
}
spawnFountain();
}, 10)
You need to use a combination of setInterval
and clearInterval
to start and stop the spawn loop. Keeping track of when the particle generation started and the current time you can determine when the interval should finish.
This is how you can make your code work. However, this approach for generating sprite particles is quite inefficient and will likely end up in performance issues. Consider using a module such as pixi-particles for this matter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eduardo Páez Rubio |