JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<h3>
Make a traffic light that cycles through each color every second
</h3>
<div id="traffic-light">
<div class="red light off"></div>
<div class="yellow light off"></div>
<div class="green light off"></div>
</div>
CSS
#traffic-light {
display: flex;
background-color: grey;
flex-direction: column;
}
.light {
display: flex;
height: 50px;
width: 50px;
border-radius: 50%;
border: 2px solid white;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
.off {
background: none;
}
JavaScript
/*
- query all elements with the 'light' class and store in an array
- using setInterval with a 1 second delay, loop through the elements
-
*/
function* lightIterator() {
let i = 0
const lights = document.getElementsByClassName('light')
for (let x = 0; x < lights.length; x++) {
lights[x].classList.toggle('off')
}
lights[i].classList.toggle('off')
console.log('test')
if (i === lights.length - 1) {
i = 0
} else {
i++
}
yield 4
}
const trafficLight = lightIterator()
setInterval(() => {
trafficLight.next()
}, 1000)