I am currently developing an app in React Native that includes a stopwatch that is stopped when the phones Gyroscope picks up a certain amount of movement. To do this I am using a setInterval to check for updates on the Gyroscope and if requirements are met, stop the timer. However, the issue arises when the setInterval is running usually 5-6 times after being stopped by both clearInterval and using a hook to check if the game has started. Currently the setInterval is set to 1 ms but it still has the same issue no matter the interval whether it be 1000ms or 10000ms.
const stopwatchINT = setInterval(() => {
if (gameStarted) {
if (data.x > 0.2) {
clearInterval(stopwatchINT)
let endTimer = performance.now()
setTimeTook(Math.round(endTimer - startTimer) + 'ms')
playSound()
setContainer(WHITE)
setGameStarted(false)
setReactionScreenDisplay({'select': 'none','singleCreate': 'none', 'reactionGame': 'none', 'flash': 'none', 'timeTook': 'block'})
}
}
}, 1)
Never mind I have solved the issue. For anyone who gets stuck on this you can enclose the setInterval in a useEffect which was what was throwing me as I forgot to pass the hooks in the array. For example:
useEffect(() => {
if (isStart) {
const timer = setInterval(() => {
if (count > 0) {
setCount(count - 1)
} else {
setCount('Times up');
clearInterval(timer);
}
}, 1000);
}
}, [isStart]);