Dani M Dani M - 2 years ago 976
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>
var images = new Array()
images[0] = "image2.jpg";
images[1] = "image3.jpg";
images[2] = "image4.jpg";
setInterval("changeImage()", 3000);
var x=0;

function changeImage()
<img id="img" src="image1.jpg">

Answer Source

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

function changeImage() {
    document.getElementById("img").src = images[x];
    x %= images.length;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download