Mahogany
Mahogany

Reputation: 529

How to automatically cycle though an array of images?

I need to make a set of images change automatically, they're traffic lights to be precise. I am using an array with a button that makes it change, but I need to to cycle through it automatically. How would I go about doing this?

<img id="light" src="N:\Computing Year 10\Year 10 CS\A452 - First Assessment\Programming\trafficlights\1red.png">

<button type="button" onclick="changeLights()">Change Lights</button> <!-- Button used to change lights-->
var lightList = [
    "1red.png",       /* index 0 */
    "2redamber.png",  /* index 1 */
    "3green.png",     /* index 2 */
    "4amber.png"      /* index 3 */
];

var index = 0;  /* New variable called 'index' set to 0 */

function changeLights() {
    index = index + 1;     /* This assigns the changeLights buttom the function of addind 1 to the value of index, which changes the traffic light */

    if (index == lightList.length) index = 0;

    var image = document.getElementById('light');
    image.src=lightList[index];
}

http://pastebin.com/Bwk7E61Y

Upvotes: 0

Views: 132

Answers (1)

Vibhesh Kaul
Vibhesh Kaul

Reputation: 2613

You can call the changeLights() function every second by using setInterval. You can read about setInterval function here. You can choose the time interval of your choice for calling the function.

window.onload = function() {
    setInterval(function(){ 

    changeLights();

    }, 1000);
}

Upvotes: 1

Related Questions