to study React.js I started converting javascript projects.
In this project, a startup button will trigger a setTimeout() function for 3 seconds before it triggers the closing function
let timer= false;
let rando= null;
let conta= 0;
let punteggio= 0;
startup.addEventListener("click", ()=>{
timer= true
rando= Math.ceil(Math.random()*1000)
centrato.innerText= rando
challenge()
})
function challenge(){
if(timer && conta< 300){
conta ++
setTimeout(challenge, 10)
}else if(conta== 300){
perso()
}else{
perso()
}
}
Then I have 2 buttons, one will reset the setTimeout() function and will record the time passed before the click, and the other will stop the setTimeout()
tre.addEventListener("click", ()=>{
if( rando% 3== 0 ){
vinto()
}else{
timer= false
}
})
notre.addEventListener("click", ()=>{
if(rando% 3== 0){
timer= false
}else{
vinto()
}
})
function vinto(){
punteggio+= conta
conta= 0;
rando= Math.ceil(Math.random()*1000)
}
function perso(){
risultato.innerText= "You got " + giri + " numbers in " + punteggio/100 + " seconds"
punteggio= 0;
conta= 0;
}
Using useState() and useEffect() on React.js I could get a reset/restart stopwatch by clicking twice or a reset/restart on a single button but being unable to stop the timer, I also tried setInterval().
I need the user to click only once to reset and repeat the setTimeout() and also to be able to stop the timer on a button click, on React.js code.
You can check the complete codepen [HERE]https://codepen.io/misterlinux/pen/yLRBMNx
2
Answers
To obtain a stop/reset/re-start single button in react you will need useEffect.
You will need 2 variables, one for the timer event listener, and another for the timer counter.
The useEffect() hook synchronizes a component with an external variable, we start the setInterval() after the isActive useState() changes.
By changing the isActive again we stop the setInterval(), we then reset the seconds counter and change the useEffect() dependency to start it again.
If you want to completely stop the setInterval() you can use a separate function to stop and reset it.
Canceling a setTimeout needs to be done with clearTimeout.
E.g.: