A similar question was posted yesterday, but I thought I'd chip in with an answer here.
JavaScript
var timeIndex = 0;
var lightIndex = 0;
var timer;
var trafficLight = document.getElementById('light');
var lights = [
{
duration: 5,
color: 'red',
image: 'red.gif'
},
{
duration: 4,
color: 'green',
image: 'green.gif'
},
{
duration: 1,
color: 'yellow',
image: 'yellow.gif'
}
]
function advanceTrafficLightTimer() {
timeIndex++;
if(timeIndex == lights[lightIndex].duration) {
timeIndex = 0;
lightIndex = lightIndex < lights.length - 1 ? lightIndex = lightIndex + 1 : 0;
trafficLight.src = lights[lightIndex].image;
trafficLight.className = lights[lightIndex].color;
}
}
timer = setInterval(advanceTrafficLightTimer,1000);
CSS
.red { border: 3px solid #f00; }
.green { border: 3px solid #0f0; }
.yellow { border: 3px solid #ff0; }
HTML
<img id="light" class="red" src="red.gif">
The JS works by updating the timeIndex
every second, and checking a variable lightIndex
against the available traffic light objects stored in the array trafficLight
. If the timeIndex
has reached the duration of the current trafficLight
, it will update the lightIndex
to the next object in the array and change the image.
You can see it working here: https://jsfiddle.net/igor_9000/a2w9g8qa/3/
This seems to be a homework problem (nothing wrong with posting questions about homework). I've left out the redamber
color, hopefully adding that in gives you a little bit of practice with the homework.
Hope that helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…