Search code examples
javascriptloopsweb-deploymentinfinite-looprepeat

Infinite Looping Javascript function, random image


I'm trying to design a looping function that pulls images from my html and places them in random places on the screen. Thus far it is working. However, I want it to repeatedly change images and position, randomly. Right now, the code runs once on load and it remains static. I've been trying to use loops and thus far they either don't work or crash the page.

window.onload = function() {
  randomPlace1('parameter');
};


function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}


var idNum = (getRandomInt(86));
setTimeout("randomPlace1()", 30000);


var i = 0;

function randomPlace1() {
  setTimeout(function() {
    document.getElementById("i" + idNum).style.display = "block";
    document.getElementById("i" + idNum).style.top = Math.floor(Math.random() * 101);
    document.getElementById("i" + idNum).style.left = Math.floor(Math.random() * 101);
    document.getElementById("i" + idNum).style.zIndex = Math.floor(Math.random() * 10);
  }, 3000);

}


Solution

  • Try using setInterval instead...

    .setTimeout() //executes the code after x seconds.
    .setInterval() //executes the code **every** x seconds.