简体   繁体   中英

how to display images slide show using javascript loop and array?

when the program runs, only the last array value image displaying on the screen and other images aren't displaying.

Here is the HTML code

<img id="mg" alt="image not found">

here is the javascript code

var images=["image", "image2","img","imag"]
test();
function test(){
   var index = 0;
   for(var count=0; count<images.length; count++){
       document.getElementById('mg').src = images[count] + ".jpg";
       document.getElementById("mg").width = "500";
       document.getElementById("mg").height = "300";
       index = index + 1;
       setTimeout(test, 1000);
       if(index + 1 > images.length){
            index = 0;
            count = 0;
    }
   }
}
function test(){
   var index = 0;
   for(var count=0; count<images.length; count++){
       ...
       setTimeout(test, 1000);
       ...
   }
}

setTimeout() here doesn't do what you think it does. It doesn't introduce a delay before going on. It actually tells the engine to go off and count 1,000 milliseconds on its own while your code here continues on.

In other words, you're calling setTimeout() for the length of the loop almost simultaneously.

I would do this differently:

const imageUrls = [
  'first.jpg',
  'second.jpg',
  'third.jpg',
  'fourth.jpg'
];

const imgEl = document.querySelector('img');
imgEl.src = imageUrls[0];

function advanceImage() {
  imgEl.src = imageUrls[imageUrls.indexOf(imgEl.src) + 1] || imageUrls[0];
}

setInterval(advanceImage, 1000);

In this case, we initialize the image to be the first URL. Then, every second we figure out what the current index is and add one to it. If we get to the part of the array where something doesn't exist, then default to the first image URL.

Ideally, you wouldn't use any JavaScript for this at all and do it with CSS, but I figured I'd share this example with you anyway.

Do you have to use the loop?  If not, try this:
<html>
    <head>
    </head>
    <body>
        <img id="mg" alt="image not found"> 
        <script type="text/javascript">
        var images=["image", "image2","img","imag"]
        test();

        var count = 0;

        function test(){
                console.log("I am executing with count at " + count);

               document.getElementById('mg').src = images[count] + ".jpg";
               document.getElementById("mg").width = "500";
               document.getElementById("mg").height = "300";

               if(count + 1 >= images.length){
                    count = 0;
                }
                else
                {
                    ++count;
                }
        }

        setInterval(test, 1000);

        </script>       
    </body>
</html>

setInterval will make sure that the function is called every second and moving the counter outside the function means that it can always be accessed and you can always get the right element in the array.

You do not need to loop on all the images since your test function only needs one image at a time. What you can do is store the currentIndex outside the function and update it at each execution. Here is an example:

 var images = ["https://api.adorable.io/avatars/100/1", "https://api.adorable.io/avatars/100/2", "https://api.adorable.io/avatars/100/3", "https://api.adorable.io/avatars/100/4"] var currentImage = 0; test(); function test() { // Update the image document.getElementById('mg').src = images[currentImage] + ".jpg"; document.getElementById("mg").width = "100"; document.getElementById("mg").height = "100"; // Update the index for the next tick currentImage += 1; if (currentImage === images.length) { currentImage = 0; } // Set next tick setTimeout(test, 1000); }
 <img id="mg" alt="image not found">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM