Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use document.createElement with elapsedTime?

I'm making a game for a school project. The premise is that there will be enemies coming from the right side of the screen, and you will have to kill them. I've managed to create them so they are shown, but i can't manage to make them not come in at the same time. Any tips on how i should go on with this?

(Sorry if this is badly formulated, i am very new to these things)

I've tried different ways of achieviving my goal trough using the elapsedTime function but i can't seem to make it work in the slightest.

function createEnemy() {
  for(var i = 0; i < antallFiender; i++) {
    var nyFiende = document.createElement("img");
    nyFiende.setAttribute("src", "tenor.gif");
    nyFiende.setAttribute("class", "zombie");
    nyFiende.style.top = Math.floor(Math.random()*800) + "px";

    barnetEl.appendChild(nyFiende);
  }
  var zombieEl = document.querySelectorAll(".zombie");
}
like image 636
Reach Avatar asked Jun 07 '26 02:06

Reach


1 Answers

You can use JavaScript setInterval function. With this function you can pass a callback in the first parameter, and a time interval (in miliseconds) as the second parameter, that is the time between the calls of your callback. So it will be something like this:

function createEnemy() {
  var nyFiende = document.createElement("img");
  nyFiende.setAttribute("src", "tenor.gif");
  nyFiende.setAttribute("class", "zombie");
  nyFiende.style.top = Math.floor(Math.random()*800) + "px";

  barnetEl.appendChild(nyFiende);
  var zombieEl = document.querySelectorAll(".zombie");
}

setInterval(createEnemy, 1000);

This way, every 1 second your function will be called to create one enemy.

If you want to stop the function from being called, you should assign the interval to a variable, so you can use clearInterval to stop it, like this:

var enemyInterval = setInterval(createEnemy, 1000);

clearInterval(enemyInterval);

Hope it helps you.

like image 194
Mayke da Rosa Herbst Avatar answered Jun 08 '26 16:06

Mayke da Rosa Herbst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!