0

I am building an website, and in the home page i have 3 divs with images changing at each 10 seconds, the problem is that the website only loads the first image after 10 seconds, i am stuck in this for a while.

Javascript

function displayNextImageTop() {
  z = z === imagesTop.length - 1 ? 0 : z + 1;
  document.getElementById("imgtop").src = imagesTop[z];
}

function displayPreviousImageTop() {
  z = z <= 0 ? imagesTop.length - 1 : z - 1;
  document.getElementById("imgtop").src = imagesTop[z];


function startTimerTop() {
  setInterval(displayNextImageTop, 10000);
}

var imagesTop = [],
  z = 0;
imagesTop[0] = "Assets/img/TV.jpg";
imagesTop[1] = "Assets/img/Telemovel.jpg";
imagesTop[2] = "Assets/img/Processador.jpg";

for HTML I call the functions like

 window.onload = function () {
            startTimerSales();
            startTimerNews();
            startTimerTop();
        }; 

} and then just call them in code

what can i do to the image load already with the page?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Filipe Cruz
  • 81
  • 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) – 001 Jun 21 '21 at 16:20

1 Answers1

0

Unless there is some interference from those 2 functions that aren't included in your code, ut appears the issue is you have your window.onload and startTimerTop functions inside the displayPreviousImageTop function. When I separate those out it seems to work fine.

function displayNextImageTop() {
  z = z === imagesTop.length - 1 ? 0 : z + 1;
  document.getElementById("imgtop").src = imagesTop[z];
}

function displayPreviousImageTop() {
  z = z <= 0 ? imagesTop.length - 1 : z - 1;
  document.getElementById("imgtop").src = imagesTop[z];

}
  function startTimerTop() {
    setInterval(displayNextImageTop, 2000);
  }

  var imagesTop = [],
    z = 0;
  imagesTop[0] = "https://images.unsplash.com/photo-1622564184875-534328710abc?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=751&q=80";
  imagesTop[1] = "https://images.unsplash.com/photo-1620165362197-5bc50d8133e8?ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2448&q=80";
  imagesTop[2] = "https://images.unsplash.com/photo-1624096402016-3a03ae59c904?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=334&q=80";

  window.onload = function() {
   // startTimerSales();
   // startTimerNews();
    displayNextImageTop()
    startTimerTop();
  };
 
<img id='imgtop' />
Kinglish
  • 23,358
  • 3
  • 22
  • 43