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

185
Views
How to clear a previous interval with React

I'm working on a simple game using React and came across a problem. So whenever you press W A S or D, an interval starts. What I want is whenever the user presses a key, the previous interval is cleared before starting the next one so that only one interval is executing at a time.

export default function useGame() {
  const [xpos, setXpos] = useState(250)
  const [ypos, setYpos] = useState(250)
  const [intervalID, setIntervalID] = useState(null)

  const handleKeypress = (e) => {
    let id = setInterval(() => {
      if (e.key === "w") {
        setYpos((prev) => {
          return (prev -= 5)
        })
      }
      if (e.key === "s") {
        setYpos((prev) => {
          return (prev += 5)
        })
      }
      if (e.key === "a") {
        setXpos((prev) => {
          return (prev -= 5)
        })
      }
      if (e.key === "d") {
        setXpos((prev) => {
          return (prev += 5)
        })
      }
    }, 100)
    setIntervalID(id)
  }

  return { handleKeypress, xpos, ypos, intervalID }


//Component file
export default function Game() {
  const { handleKeypress, xpos, ypos, intervalID } = useGame()

  useEffect(() => {
    window.addEventListener("keypress", (e) => {
    console.log(intervalID)
      if (intervalID) {
        clearInterval(intervalID)
      }
      handleKeypress(e)
    })
    return () => {
      window.removeEventListener("keypress", null)
    }
  }, [])

  return (
    <div
      className="character"
      style={{
        position: "absolute",
        left: `${xpos}px`,
        top: `${ypos}px`,
      }}
    ></div>
  )
}

I've tried storing the interval ID in state but its always undefined in other functions or other parts of the code. How would you guys go about solving this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need to store interval id returned by setInterval and pass it to clearInterval whenever you want to clear that interval.

function App() {

        const [count, setCount] = useState(0);
        const [intervalId, setIntervalId] = useState(null);

        const startCounting = () => {
            const id = setInterval(()=>{
                setCount(prevCount => prevCount + 1);
            }, 1000);
            setIntervalId(id);
        }

        return (<div>
            <div>{count}</div>
            <button onClick={startCounting}>Start Interval</button>
            <button onClick={()=>clearInterval(intervalId)}>Stop Interval</button>
        </div>);

}

In you question you have created separate interval depending on each condition, and every interval will have different interval id. so better put all condition into single setInterval and return its interval id.

import { useState } from "react"

export default function useGame() {
    const [xpos, setXpos] = useState(250)
    const [ypos, setYpos] = useState(250)
    const [intervalId, setIntervalId] = useState(null);

    const handleKeypress = (e) => {
        const id = setInterval(() => {
            if (e.key === "w") {
                setYpos((prev) => {
                    return (prev -= 5)
                })
            }
            if (e.key === "s") {
                setYpos((prev) => {
                    return (prev += 5)
                })
            }
            if (e.key === "a") {
                setXpos((prev) => {
                    return (prev -= 5)
                })
            }
            if (e.key === "d") {
                setXpos((prev) => {
                    return (prev += 5)
                })
            }
        }, 100);
        setIntervalId(id);
    }

    return { handleKeypress, xpos, ypos, intervalId }
}
about 4 years ago · Juan Pablo Isaza Report

0

import { useState } from "react"

export default function useGame() {
  const [intervalId, setIntervalId] = useState(Number(0));
  const [xpos, setXpos] = useState(250)
  const [ypos, setYpos] = useState(250)

  const handleKeypress = (e) => {
    if (e.key === "w") {
      if(intervalId > 0) {
        clearInterval(intervalId);
      }
      let id = setInterval(() => {
        setYpos((prev) => {
          return (prev -= 5)
        })
      }, 100)
      setIntervalId(Number(id));
    }
    if (e.key === "s") {
      if(intervalId > 0) {
        clearInterval(intervalId);
      }
      let id = setInterval(() => {
        setYpos((prev) => {
          return (prev += 5)
        })
      }, 100)
      setIntervalId(Number(id))
    }
    if (e.key === "a") {
      if(intervalId > 0) {
        clearInterval(intervalId);
      }
      let id = setInterval(() => {
        setXpos((prev) => {
          return (prev -= 5)
        })
      }, 100)
      setIntervalId(Number(id))
    }
    if (e.key === "d") {
      if(intervalId > 0) {
        clearInterval(intervalId);
      }
      let id =setInterval(() => {
        setXpos((prev) => {
          return (prev += 5)
        })
      }, 100)
      setIntervalId(Number(id))
    }
  }

  return { handleKeypress, xpos, ypos }
}

clearInterval

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!