Traffic Light
Build a traffic light that cycles green, yellow, red and loops forever. The demo mounts two: a vertical one starting on green and a horizontal one starting on red.
Requirements
- Each light stays lit for its own time: red 4000 ms, yellow 500 ms, green 3000 ms. The order is green, then yellow, then red, then green again.
TrafficLightreads the colours, durations and order from itsconfigprop and starts oninitialColor, so the two lights run independently.- Only the current light is lit; the others stay dim.
- Assistive technology hears the current light through a polite live announcement such as "Current light: green"; the purely visual lights are hidden from it.
- No timer survives the component's unmount.
Hints
Hint 1
The state is one string, the current colour. Everything else — which lamp is lit, how long to wait, what comes next — is a lookup in config.
Hint 2
setInterval fires at one fixed rate and the three durations differ. Schedule a single setTimeout for the current light's duration in an effect keyed on the current colour; when it fires and the colour changes, the effect runs again and arms the next one.
Hint 3
Return clearTimeout from the effect: it cancels the pending change on unmount, and React also runs it before re-running the effect, so there is never more than one timer.
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.