0

I know this is a very noob question, looked up a couple of examples but me being a beginner I'm having trouble implementing it in my code.

I think the title is pretty clear cut, I would like that the loop starts with a random item, and continues picking random items out of the array.

var bgImageArray = [
"link1" , "link2" , "link3"
]

base = "https://lh3.googleusercontent.com/pw/";
bgImageArray.forEach(function(img){
    new Image().src = base + img; 
});

function backgroundSequence() {
  window.clearTimeout();
  var k = 0;
  for (i = 0; i < bgImageArray.length; i++) {
    setTimeout(function(){ 
      document.getElementById('animated-bg').style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center";
    if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (60000 / tempo.value))} else { k++; }      
    }, (60000 / tempo.value) * i) 
  }
}
``
be4tt
  • 1
  • 1
    It would be simpler to simply shuffle the array, and then iterate sequentially. see: [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – pilchard Jan 26 '21 at 10:45
  • Do you want to display every background ONCE randomly, or loop indefinitely ? – Simon Jan 26 '21 at 10:47

2 Answers2

0

Perhaps better like this

Update: Missed the random part

let bgImageArray = ["link1", "link2", "link3"];
const base = "https://lh3.googleusercontent.com/pw/";
bgImageArray = bgImageArray.map(img => new Image().src = base + img);

function backgroundSequence() {
  const rndImageSrc = bgImageArray[Math.floor(Math.random()*bgImageArray.length)].src;
  document.getElementById('animated-bg').style.background = "url(" + rndImageSrc + ") no-repeat center center";
}
let tId = setInteval(backgroundSequence,tempo*1000);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

use this code for select random element from array

var bgImageArray = ["link1", "link2", "link3"];

const random = Math.floor(Math.random() * bgImageArray.length);
console.log(random, bgImageArray[random]);
Mohit RaiYani
  • 236
  • 1
  • 6