Joshua Bitton
Joshua Bitton

Reputation: 403

React setInterval

I'm trying to make a function that will increase a time variable every second. So I do this:

 const [time, setTime]=useState(0)
function startRecord(){
start()
setClicked(true)
setInterval(()=>{
    setTime(prev=>prev+1)

},1000)
}

function stopRecord(){
setTime(0)
 stop()
 setClicked(false)
}

But the problem I'm encountering is that whenever I reset the time setTime(0), and then I restart setting the time, the time that is being displayed increments every milisecond for some reason. Here is a video: https://gyazo.com/4335c5c05a86c4f1d62271a8bc4e4fdd Any idea why this is happening?

Upvotes: 1

Views: 57

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

Store the interval ID in state (or in a ref), and when you do setClicked(false), also clear the interval:

const [time, setTime] = useState(0)
const [intervalId, setIntervalId] = useState();
function startRecord() {
    start()
    setClicked(true)
    setIntervalId(setInterval(() => {
        setTime(prev => prev + 1)
    }, 1000));
}

function stopRecord() {
    setTime(0)
    stop()
    setClicked(false)
    clearInterval(intervalId);
}

Upvotes: 2

Related Questions