Kanwarjeet Singh
Kanwarjeet Singh

Reputation: 745

unable to clear interval, React native

I created a timer function it's working but when I click clearInterval it's not working, timer still going on.

Here is my function to start timer. Maximum limit for timer is 60sec

const StartRecord = ()=>{ 
const timeout = setInterval(() => {
        if (time != 60) {
          setTime(prevState => prevState + 1);
        }
      }, 1000);
      console.log(timeout);

      if (time == 60) {
        clearInterval(timeout);
      }
}

here is my function to stop timer

  const onStopRecord = () => {
    clearInterval(time);
}

can anyone tell me why it's not working?

Upvotes: 0

Views: 56

Answers (2)

shammi
shammi

Reputation: 1409

you can use useEffect to do this task

useEffect(() => {
 let interval
 if(time != 60){
    interval = setInterval(() => setTime((prev) => prev + 1), 1000);      
 }
 return () => clearInterval(interval);
}, [time])

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 10081

You are trying clearInterval using time. It should be timeout

const onStopRecord = () => {
    clearInterval(timeout);
}

Upvotes: 1

Related Questions