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

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

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 Relatório

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 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