Dani M Dani M - 7 months ago 341
Javascript Question

How to do a continual loop for my traffic light sequence javascript?

I am trying to do a traffic light sequence which runs on a timed basis automatically without user input . I have now got the code working but it only runs through once and then stops so how can I change this so it keeps going?
Here is my code:

<!DOCTYPE html>
<html>
<head>
<script>
var images = new Array()
images[0] = "image2.jpg";
images[1] = "image3.jpg";
images[2] = "image4.jpg";
setInterval("changeImage()", 3000);
var x=0;

function changeImage()
{
document.getElementById("img").src=images[x]
x++;
}
</script>
</head>
<body>
<img id="img" src="image1.jpg">
</body>
</html>

Answer

Apply the remainder assignment %= to the counter with the length of the array.

function changeImage() {
    document.getElementById("img").src = images[x];
    x++;
    x %= images.length;
}