0

What my code does:

  • stays blank for 3 seconds
  • displayes index 1 of my list of image
  • loops through the list and restarts at index 0

<div id="background" class="text-center background">

    <script type = "text/javascript">
        var background = document.getElementById("background");
        var currentPos = 0;
        var imagesb = ["/images/indeximg0.jpg", "/images/indeximg11.jpg", "/images/indeximg33.jpg", "/images/indeximg44.jpg", "/images/indeximg55.jpg"], i = 0;

        function changeimage()
        {
            if (++currentPos >= imagesb.length)
                currentPos = 0;

            background.style.backgroundImage = "url(" + imagesb[currentPos] + ")";
        }
        setInterval(changeimage, 3000);
    </script>

</div>

What I want it to do:

  • no 3 second blank background delay
  • starts with index 0

What I tried:

  • I set currentPos = 4

this fixed the issue with the first image being displayed but the 3 second delay was still there. I also don't like this way of doing it because I would have to manually change currentPos if i add or remove images to the list

  • I tried to initialize my background before the first div to fix the 3 second back background with he following code:

<script type = "text/javascript">
    background.style.backgoundImage= "url(/images/indeximg0.jpg)";
</script>

nothing changed. still had the 3 second delay

jgrewal
  • 342
  • 1
  • 10
  • Does this answer your question? [Execute the setInterval function without delay the first time](https://stackoverflow.com/questions/6685396/execute-the-setinterval-function-without-delay-the-first-time) – MrUpsidown Jul 27 '21 at 08:13

1 Answers1

1

You should

  1. Call the function once before the setInterval() and
  2. When doing ++currentPos you are actually incrementing the variable so the first time you set the background, the value is already 1. The easiest way to change that is to set the background before your if test.

var background = document.getElementById("background");
var currentPos = 0;
var imagesb = ["https://via.placeholder.com/100", "https://via.placeholder.com/200", "https://via.placeholder.com/300"];

function changeimage() {

  background.style.backgroundImage = "url(" + imagesb[currentPos] + ")";
  
  if ((++currentPos) >= imagesb.length) {
    currentPos = 0;
  }
}

changeimage();
setInterval(changeimage, 1000);
body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
}

.background {
  height: 100%;
  width: 100%;
}
<div id="background" class="text-center background"></div>
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131