How to make sure setInterval doesn't stack if it is already running?

60 Views Asked by At

I have a class with the function start() which generates particles after a given interval, but if you call the start() function more than once, the clearInterval() in the stop() function doesn't stop it anymore.

Here is the code:

class ParticleGenerator {
  constructor(pgPhyEngine, x, y, width, height, particleSizeRange = {
    min: 3,
    max: 10
  }, spawnRate = 100, particlesPerSpawn = 1, velXRange = {
    min: -15,
    max: 15
  }, velYRange = {
    min: -15,
    max: 15
  }, particleColorsArray = ["#ff8000", "#808080"]) {
    this.parent = pgPhyEngine;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.particleSizeRange = particleSizeRange;
    this.velXRange = velXRange;
    this.velYRange = velYRange;
    this.particleColors = particleColorsArray;
    this.spawnRate = spawnRate;
    this.spawning = false;
    this.particlesPerSpawn = particlesPerSpawn;
  }

  start() {
    this.spawnManager = setInterval(() => {
      for (var i = 0; i < this.particlesPerSpawn; i++) {
        this.parent.createParticle((this.x - this.width / 2) + (random(0, this.width)), (this.y - this.height / 2) + (random(0, this.height)), random(this.particleSizeRange.min, this.particleSizeRange.max), pickRandomItemFromArray(this.particleColors), true, random(this.velXRange.min, this.velXRange.max), random(this.velYRange.min, this.velYRange.max));
      }
    }, this.spawnRate);
  }

  stop() {
    // This doesn't work if the start() function is called more than once.
    clearInterval(this.spawnManager);
  }
}

1

There are 1 best solutions below

0
Kavan Prajapati On BEST ANSWER

Initialize spawnManager as null like below,

this.spawnManager = null;

In your start function simply clear the interval first like this,

start(){
  if (this.spawnManager) {
    this.stop()
  }
  this.spawnManager = setInterval(() => {
    for (var i = 0; i < this.particlesPerSpawn; i++) {
      this.parent.createParticle((this.x - this.width / 2) + (random(0, this.width)), (this.y - this.height / 2) + (random(0, this.height)), random(this.particleSizeRange.min, this.particleSizeRange.max), pickRandomItemFromArray(this.particleColors), true, random(this.velXRange.min, this.velXRange.max), random(this.velYRange.min, this.velYRange.max));
    }
  }, this.spawnRate);
}

stop() {
  // This doesn't work if the start() function is called more than once.
  clearInterval(this.spawnManager);
}