JSFiddle - React, Tailwind, and code Playground

by igor_9000

HTML

<img id="light" class="red" src="red.gif">

CSS

.red { border: 3px solid #f00; }
.green { border: 3px solid #0f0; }
.yellow { border: 3px solid #ff0; }

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)














































// (C) 2016 Adam Konieska adamkonieska.com