Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda