asasas asasas -4 years ago 115
Javascript Question

How to add a timer for images in JavaScript?

I've been working on this code which displays the next traffic light when a button is pressed. Now I am trying to diplay the images in the array every 3 seconds. I have tried using setTimeOut in my code but my code juts stays on the first traffic light.


<!DOCTYPE html>

<h1>JavaScript Code</h1>
<p>Traffic Light</p>

<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>

var list = ["only red1.jpg","red-yellow 2.jpg", "green3.jpg","yellowonly4.jpg"];
var nextlight = 0;
var timer;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
firstlight.src = list[nextlight];

timer = setInterval(ChangeLight, 3000);

Answer Source


timer = setInterval("ChangeLight", 3000);

Put it out of the function ^^

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download