Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda