Senyd Senyd - 17 days ago 7
HTML Question

Cycling through a whole array after button press

To summarize my current efforts, I have made a very basic program that, upon a button press, moves to the next section of a traffic light (starts on red, upon press goes to amber etc.), as each image for the traffic light is stored in an array. This does work as intended but I now need to change this code to make it so that upon a button press, rather than just going to the next thing in the array, it cycles through all of them for a certain amount of time, simulating a traffic light. I could not for the life of me find out where to start, and everything I have tried (

setTimeout
,
setInterval
) has not worked as intended.

Here is my code (without any additions/changes):

<!DOCTYPE html>
<html>
<body>

<h1 style="font-size:300%">Changing Traffic Lights</h1>
<p>
<button type="button" onclick="changeLights()">Change Lights</button>
</p>

<img id="light" src="traffic-light-red.jpg">

<script>
var list = [
"traffic-light-red.jpg",
"traffic-light-amber.jpg",
"traffic-light-green.jpg"
];

var index = 0;

function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src=list[index];
}

</script>

</body>
</html>

Answer

Something like this?

// Array of light images:
var list = [
    "traffic-light-red.jpg",
    "traffic-light-amber.jpg",
    "traffic-light-green.jpg"
];

// Counter to keep track of which image is displayed
var index = 0;

// Get DOM references:
var btnStart = document.getElementById("btnChange");
var btnStop = document.getElementById("btnStop");
var image = document.getElementById('light'); 

// Variable to keep track of timer
var timer = null;

// Wire click events for buttons:
btnStart.addEventListener("click", changeLights);
btnStop.addEventListener("click", stopLights);


function changeLights() {
    index++;  // Bump up index 

    // Reset index to 0 if it's reached its max
    index = index == list.length ? 0 : index;

    // Change the image source and alternate text
    image.src = list[index];
    image.alt = list[index];

    // Make this function call itself again in approx. 1.5 seconds
    timer = setTimeout(changeLights, 1500);
}

function stopLights(){
 // Stop the timeout
 clearTimeout(timer);
}
<h1 style="font-size:300%">Changing Traffic Lights</h1>
<p> 
<button type="button" id=btnChange>Change Lights</button>
<button type="button" id=btnStop>Stop Lights</button>
</p>
<img id="light" src="traffic-light-red.jpg" alt="traffic-light-red.jpg">

Comments