<!DOCTYPE html>
<html>
<head>
<title>Traffic Light</title>
<style>
.traffic-light {
width: 100px;
height: 300px;
background-color: #333;
border-radius: 10px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 10px;
}
.light {
width: 80px;
height: 80px;
border-radius: 50%;
margin: 5px;
}
.red { background-color: #c0392b; }
.yellow { background-color: #f1c40f; }
.green { background-color: #27ae60; }
.off { background-color: #7f8c8d; } /* Dimmed color for off state */
</style>
</head>
<body>
<div class="traffic-light">
<div class="light red" id="red"></div>
<div class="light yellow" id="yellow"></div>
<div class="light green" id="green"></div>
</div>
<script>
const redLight = document.getElementById('red');
const yellowLight = document.getElementById('yellow');
const greenLight = document.getElementById('green');
function setLight(redState, yellowState, greenState) {
redLight.classList.toggle('off', !redState);
yellowLight.classList.toggle('off', !yellowState);
greenLight.classList.toggle('off', !greenState);
}
let currentLight = 'red';
setInterval(() => {
switch (currentLight) {
case 'red':
setLight(true, false, false);
currentLight = 'green';
break;
case 'green':
setLight(false, false, true);
currentLight = 'yellow';
break;
case 'yellow':
setLight(false, true, false);
currentLight = 'red';
break;
}
}, 2000); // Change every 2 seconds (adjust as needed)
</script>
</body>
</html>
Key improvements in this version:
- Clearer Styling: Uses CSS classes for styling, making it easier to understand and modify. The
off
class dims the lights when they are not active, making the light changes more visually distinct. setLight
function: This function simplifies the logic for turning lights on and off by toggling theoff
class. This makes thesetInterval
logic much cleaner.- Comments: Added comments to explain the code's functionality.
- Realistic Timing: Adjusted the timing to be more like a real traffic light (you can customize this further). Red, then green, then yellow.
- HTML Structure: Uses a
div
with a class oftraffic-light
to contain the lights, making it easier to style and position the entire unit.
This improved version provides a more robust and understandable implementation of a traffic light in JavaScript. You can easily copy and paste this code into an HTML file and open it in a browser to see the traffic light in action. You can adjust the timing and colors in the CSS and JavaScript to customize the behavior.