JavaScript Traffic light System
How to Build a Traffic light System in Vanilla JavaScript
Watch the full tutorial here:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<script src="./main.js" defer></script>
<title>Traffic Light</title>
</head>
<body>
<span id="waitTime"></span>
<div id="trafficlight">
<span class="light" id="red"></span>
<span class="light" id="yellow"></span>
<span class="light" id="green"></span>
</div>
</body>
</html>
css
#trafficlight {
display: flex;
flex-direction: column;
gap: 5px;
}
.light {
width: 30px;
height: 30px;
border-radius: 50px;
border: 2px solid #131313;
opacity: .5;
}
#red {
background-color: red;
}
#yellow {
background-color: yellow;
}
#green {
background-color: green;
}
javascript
let lights = [
{ element: document.getElementById("red"), duration: 5000 },
{ element: document.getElementById("yellow"), duration: 3000 },
{ element: document.getElementById("green"), duration: 7000 },
];
let currentIndex = 0;
function changeLight() {
lights.forEach(light => light.element.style.opacity = "0.3");
let currentLight = lights[currentIndex];
currentLight.element.style.opacity = "1";
currentIndex = (currentIndex + 1) % lights.length;
setTimeout(changeLight, currentLight.duration);
}
changeLight();