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

188
Views
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 answers
Answer question

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 Report

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