0

I just was wondering what a code that could loop an array of images may look like. I have an example but cannot see why it does not work:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" language="JavaScript">
    var i =0;
    var trafficarray=["1.gif","2.gif","3.gif","4.gif"];
    var image = document.getElementById("trafficlights");

    function cycle(){
      i+=1;
      document.getElementById("trafficlights").src=trafficarray[i];
      if (i>2) {i=-1};
    }
  </script>
</head>

<body>
  <img src="1.gif" id="trafficlights">
  <button onClick="setInterval(cycle,1000)">click me</button>
</body>

4
  • Use a recursive function together with setTimeout() Commented Feb 10, 2016 at 19:13
  • @Shashank The document initializes with 1.gif being shown. The function that changes the images is only invoked after the user clicks on the button. Commented Feb 10, 2016 at 19:14
  • @villecoder Got it, thanks. Commented Feb 10, 2016 at 19:14
  • Works fine for me jsfiddle.net/awkwvgyj Commented Feb 10, 2016 at 19:21

2 Answers 2

2

Your code does work. Perhaps you mean that the images are not loading. In this case, make sure "1.gif" and the rest of the files exist in the same directory that your webpage is served on, otherwise you may see broken links.

Sign up to request clarification or add additional context in comments.

Comments

0

Never mind all! I have fixed it:

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" language="JavaScript">
var i =0;
var trafficarray=["1.gif","2.gif","3.gif","4.gif"];
var image = document.getElementById("trafficlights");

function cycle()
{
i+=1;
document.getElementById("trafficlights").src=trafficarray[i]
if (i>2) {i=-1};
}
</script>
</head>

<body>

<img src="1.gif" id="trafficlights">
<button onClick="setInterval(cycle,1000)">click me</button>
</body>
</html>

Or alternatively:

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" language="JavaScript">
var i =0;
var trafficarray=["1.gif","2.gif","3.gif","4.gif"];
var image = document.getElementById("trafficlights");

function cycle()
{
i+=1;
document.getElementById("trafficlights").src=trafficarray[i]
if (i>2) {i=-1};
}
</script>
</head>

<body>

<img src="1.gif" id="trafficlights">
<button onClick="cycle()">click me</button>
</body>
</html>

1 Comment

I'm not sure I get it. What did you fix? Your first code is the same thing you posted in your question. And the second code just makes it change on click instead of on a timer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.