Home > Software engineering >  how to spawn 1 to 3 objects randomly many times Javascript
how to spawn 1 to 3 objects randomly many times Javascript

Time:10-24

I am trying to spawn 1 to 3 monsters randomly many times in Javascript, this is the code i have for now but this only makes it randomly spawn when i refresh and then it keeps spawning the same amount of monsters the whole time.

function spawnMonster(){ setInterval( function(){ for(var i = 0; i < randomMonster; i ){ monsterDiv.innerHTML = monsterPic; outputDiv.innerHTML = "monstrene angriper.</br>" outputDiv.innerHTML; } }, Math.floor(Math.random()* 3000) 1000 ); }

CodePudding user response:

I'm assuming randomMonster is the random value between 1-3.

When the variable is set, it (obviously) doesn't change as you did describe.

Just make sure you calculate a new randomMonster -value inside the setInterval function:

function spawnMonster(){
  setInterval(function(){
    const randomMonster = Math.floor(Math.random() * 3)   1;
    for(var i = 0; i < randomMonster; i  ){ 
      monsterDiv.innerHTML  = monsterPic; 
      outputDiv.innerHTML = "monstrene angriper.</br>"   outputDiv.innerHTML;
    }
  }, Math.floor(Math.random() * 3000)   1000);
}
  • Related