JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<div class="traffic-light">
<div class="light" id="red"></div>
<div class="light" id="yellow"></div>
<div class="light" id="green"></div>
</div>
CSS
body {
display: flex;
align-items: center;
justify-content: center;
margin: 0;
background-color: #f0f0f0;
}
.traffic-light {
display: flex;
flex-direction: column;
align-items: center;
}
.light {
width: 50px;
height: 50px;
border-radius: 50%;
margin: 1px;
}
#red {
background-color: #ff0000;
}
#yellow {
background-color: #ffff00;
}
#green {
background-color: #00ff00;
}
JavaScript
function trafficSignals() {
function switchLight(color, duration) {
// Update the background color based on the color parameter
document.getElementById(color.toLowerCase()).style.opacity = 1;
// Log the current traffic light color to the console
console.log(`Traffic light: ${color}`);
// Return a promise that resolves after the specified duration
return new Promise(resolve => {
setTimeout(() => {
// Reset the background color after the duration
document.getElementById(color.toLowerCase()).style.opacity = 0.3;
resolve();
}, duration);
});
}
async function runTraffic() {
while (true) {
await switchLight("Green", 5000);
await switchLight("Yellow", 5000);
await switchLight("Red", 5000);
}
}
runTraffic();
}
trafficSignals();