Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

image loop infinitely after clicking

something wrong with my this code, the images are supposed to loop infinitely every 1 second after i click the start button. but when i clicked, it showed only the first image then stuck.

<!DOCTYPE html>
<html>

<head>
  <h1> The traffic script</h1>

  <p> <button type="button" onClick="Cool()"><h2>Start</h2></button> </p>

  <script>
    function Cool() {

      setInterval(function() {
        Timer()
      }, 1000);
      //This will call the Timer function - units are milliseconds

      function Timer() // Complete the Timer() function by adding conditional statements to display the images
      {
        var list = [
          "https://i.ibb.co/Km3c7Lb/capture0002.jpg",
          "https://i.ibb.co/DL4N0K6/capture0002.jpg",
          "https://i.ibb.co/VqnpV4G/capture0001.jpg"

        ];

        var index = 0;
        index = index + 1;
        if (index == list.length) index = 1;
        var image = document.getElementById('red');
        image.src = list[index];
      }
    }
  </script>
</head>

<body>
  <img id="red" src="https://i.ibb.co/Km3c7Lb/capture0002.jpg">
</body>

</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is you use the same index every time.

   var index = 0;
    index = index + 1;
    if (index == list.length) index = 1;
    var image = document.getElementById('red');
    image.src=list[index];

It is always 1.

  1. You need to move the declaration out of the function.
  2. Increment it AFTER you use it.
  3. Also, you should reset it to 0, not 1, when it reaches the end.

outside of callback

   var index = 0;

in callback

    var image = document.getElementById('red');
    image.src=list[index];
    index = index + 1;
    if (index == list.length) index = 0;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading