Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Is there something wrong with my setInterval function Implementation?

$
0
0

I'm currently trying to create a stopwatch component using React Native and the setInterval function to increment a counter and set the new value to state like so:

Play Function(this runs after hitting the play button)

  const [isRunning, setisRunning] = useRecoilState(runState);  const [time, setTime] = useRecoilState(timeState);  const [timerRef, setTimerRef] = useState(0);  const Play = useCallback(() => {  window.clearInterval(interval);                       //clear the interval   if (isRunning === false) {                           //set the isRunning state to true  setisRunning((isRunning) => !isRunning);  interval = window.setInterval(() => {               //setInterval operation    setTime((previousTime) => previousTime + 1);  }, 100);  setTimerRef(interval);                             //setTimer reference to pause}}, [time]);

Pause Function(this runs after hitting the pause button)

  const Pause = () => {  if (isRunning === true) {  setisRunning((isRunning) => !isRunning);  window.clearInterval(timerRef);  }  };

My problem is that the timer tends to speed up erratically an as such I'm not able to use the time value passed. I'm not sure where I am going wrong, kindly assist.


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>