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

189
Vistas
React snake Game - Snake is not moving (setInterval problem)

You can check the app from this; Sandbox

The logic of the snake movement is removing one square from its back and adding a new head basically. This creates an appearance like moving. But my interval doesn't seem to work correctly.

It works only for once then it's doing the same thing over and over again. Which means that state is not changing at all after one time.

I saw this in a video where someone was developing this game exactly this way but it was working. I can't see what's wrong with this code, thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I saw your question. It was really interesting. The problem is this one.

useEffect(() => {
    setInterval(moveSnake, 1000);
  }, []);

setInterval(moveSnake, 1000). This is using origin moveSnake. As functional components overwrite the whole state and functions, moveSnake changes. I think pointer to the array changes. And as it's using the origin pointer, setInterval can not change the state. I think you can update as follow.

useEffect(() => {
        setTimeOut(moveSnake, 1000);
      }, [snakeDots]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

The "hidden" trick is that you are using snakeDots in your moveSnake method. Thus you will want to wait until it's done updating to trigger a new call.

You can make use of both useEffect and setTimeout to set a new timeout every time the snakeDots have been updated in the state. For example:

useEffect(() => {
  setTimeout(moveSnake, 1000);
}, [snakeDots]);
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