Stopwatch React.js 应用程序,单击一个按钮立即重置/重新启动计时器

huangapple go评论60阅读模式
英文:

Stopwatch React.js application, with immediate reset/re-start timer on a single button click

问题

为了学习React.js,我开始将JavaScript项目转化。

在这个项目中,启动按钮将触发一个3秒的setTimeout()函数,然后触发关闭函数。

然后我有两个按钮,一个将重置setTimeout()函数并记录单击前经过的时间,另一个将停止setTimeout()。

使用useState()和useEffect()在React.js上,我可以通过双击获得重置/重新启动的秒表,也可以通过单击按钮进行重置/重新启动,但无法停止计时器,我还尝试了setInterval()。

我需要用户只需单击一次即可重置并重复setTimeout(),还需要能够在单击按钮上停止计时器的React.js代码。

您可以在这里查看完整的代码pen。

英文:

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>

答案1

得分: 0

Canceling a setTimeout needs to be done with clearTimeout.

E.g.:

let timeoutId = setTimeout( function(){}, 1000 );
clearTimeout( timeoutId );
英文:

Canceling a setTimeout needs to be done with clearTimeout.

E.g.:

let timeoutId = setTimeout( function(){}, 1000 );
clearTimeout( timeoutId );

答案2

得分: 0

要在React中获取一个停止/重置/重新启动的单按钮,您需要使用useEffect。
<button onClick={ () => setIsActive(x => !x) }>
  启动
</button>
<button onClick={reset}>
  重置
</button>
您需要两个变量,一个用于计时器事件监听器,另一个用于计时器计数器。
useEffect(() => {
  let interval = null;
  if (isActive) {

    interval = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 500);

  } else if (!isActive && seconds !== 0) {
    clearInterval(interval);
    setSeconds(0)
    setIsActive(!isActive);
  }
  
  return () => {
    clearInterval(interval);
  }
}, [isActive, seconds]);

function reset() {
  setSeconds(0);
  setIsActive(false);
}
**useEffect()钩子**用于将组件与外部变量同步,我们在isActive useState() 更改后开始setInterval()。

通过再次更改isActive,我们停止setInterval(),然后重置秒数计数器并更改useEffect()的依赖项以再次启动它。

如果要完全停止setInterval(),可以使用单独的函数来停止和重置它。
英文:

To obtain a stop/reset/re-start single button in react you will need useEffect.

&lt;button onClick={ ()=&gt; setIsActive((x)=&gt; !x) }&gt;
  start
&lt;/button&gt;
&lt;button onClick={reset}&gt;
  Reset
&lt;/button&gt;

You will need 2 variables, one for the timer event listener, and another for the timer counter.

useEffect(() =&gt; {
  let interval = null;
  if (isActive) {

    interval = setInterval(() =&gt; {
      setSeconds(seconds =&gt; seconds + 1);
    }, 500);

  } else if (!isActive &amp;&amp; seconds !== 0) {
    clearInterval(interval);
    setSeconds(0)
    setIsActive(!isActive);
  }
  
  return () =&gt; {
    clearInterval(interval);
  }
}, [isActive, seconds]);

function reset() {
  setSeconds(0);
  setIsActive(false);
}

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.

huangapple
  • 本文由 发表于 2023年4月7日 00:46:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定