Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
how to synchronize 2 components(traffic light) that show 2 different colors based on dynamic on/off times

I have 2 components that represent a traffic light that shows red and green colors and they are synchronized with each other. The time for each color of the traffic light will be dynamic, based on the traffic data we get but they are synchronized (if one traffic light has a green color for 8 seconds, the other one must have red for 2 seconds (assuming the total would be 10 seconds).

The code below works, but what if every 10 seconds(i will call an API) I want to change their green/red times. How would you approach it?

 const [bottomToUp, setBottomToUp] = useState({
    redLight: false,
    greenLight: true,
    greenOnTime: 6,
    redOnTime: 4,
  });

  const [rightToLeft, setRightToLeft] = useState({
    redLight: true,
    greenLight: false,
    greenOnTime: 4,
    redOnTime: 6,
  });

  useEffect(() => {
    setTimeout(
      () => {
        setBottomToUp((prevState) => ({
          ...prevState,
          redLight: !prevState.redLight,
          greenLight: !prevState.greenLight,
        }));
      },
      bottomToUp.redLight
        ? bottomToUp.greenOnTime * 1000
        : bottomToUp.redOnTime * 1000
    );
  }, [bottomToUp]);

  useEffect(() => {
    setTimeout(
      () => {
        setRightToLeft((prevState) => ({
          ...prevState,
          redLight: !prevState.redLight,
          greenLight: !prevState.greenLight,
        }));
      },
      rightToLeft.redLight
        ? rightToLeft.greenOnTime * 1000
        : rightToLeft.redOnTime * 1000
    );
  }, [rightToLeft]);


       return (<div>
          <TrafficLight
            RedOn={rightToLeft.redLight}
            GreenOn={rightToLeft.greenLight}
          />
          <TrafficLight
            RedOn={bottomToUp.redLight}
            GreenOn={bottomToUp.greenLight}
          />
      </div>)
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If the traffic lights are dependent on each other, that should be reflected in the code. The synchronisation could be done a bit more effectively without separating the state of the traffic lights. Aside from keeping a single state, if you want to keep red and green lights in sync you should keep one fixed and calculate the other from the total length and the fixed light length.

const [bottomToUp, setBottomToUp] = useState({
  greenLight: true,
  greenOnTime: 1,
  totalSemaphoreTime: 3,
})
/** Using ref here because the state changes would cause the useEffect hook to reevaluate and clear the previous timeout before it was completed */
const bottomToUpRef = useRef(bottomToUp)
bottomToUpRef.current = bottomToUp

const fetchNewGreenOnTimeFromAPI = () => {
  const newGreenOnTime = getFromAPI()
  setBottomToUp(prev => ({ ...prev, greenOnTime: newGreenOnTime }))
}

useEffect(() => {
  let timeoutId

  const timeout = () => {
    return setTimeout(
      () => {
        setBottomToUp(prevState => ({
          ...prevState,
          greenLight: !prevState.greenLight,
          timerStarted: false,
        }))
        timeoutId = timeout()
      },
      bottomToUpRef.current.greenLight
        ? bottomToUpRef.current.greenOnTime * 1000
        : (bottomToUpRef.current.totalSemaphoreTime -
            bottomToUpRef.current.greenOnTime) *
            1000 /** Only using the greenLight as parameter since red light is dependent on green light */,
    )
  }

  timeoutId = timeout()

  return () => {
    clearTimeout(
      timeoutId,
    ) /** You should always clear timeout when component unmounts */
  }
}, [])

return (
  <div>
    {/** Switched the right to left semaphore values to be reflected from the bottomToUp state since they are dependent */}
    <TrafficLight
      RedOn={bottomToUp.greenLight}
      GreenOn={!bottomToUp.greenLight}
    />
    <TrafficLight
      RedOn={!bottomToUp.greenLight}
      GreenOn={bottomToUp.greenLight}
    />
  </div>
)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!