Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  79] [ 5]  / answers: 1 / hits: 24971  / 8 Years ago, thu, april 28, 2016, 12:00:00

Here is my code for a traffic light's sequences. I was wondering how I could add a timer in to change the traffic light colour every 3 seconds, for example, when the button is clicked. Thanks!



<!DOCTYPE html> 
<html>
<body>
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id=light src=./assets/red.jpg>
<button type=button onclick=changeLights()>Change Lights</button>
<script>
var list = [./assets/red.jpg,./assets/redamber.jpg, ./assets/green.jpg,./assets/amber.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>

More From » html

 Answers
3

Use the setInterval function.



The first parameter is the function you want to call and the second parameter is how often it should be called, in milliseconds.



var timer = setInterval(changeLights,3000);




var list = [./assets/red.jpg,./assets/redamber.jpg,     ./assets/green.jpg,./assets/amber.jpg ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src=list[index]; }
var timer = setInterval(changeLights,3000);

<h1>JavaScript Task 3</h1> 
<p>This is my Traffic Light script</p>
<img id=light src=./assets/red.jpg> <button type=button
onclick=changeLights()>Change Lights</button>




[#62362] Wednesday, April 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julieth

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;