代码之家  ›  专栏  ›  技术社区  ›  Brian Millot

计时器不会以clearInterval停止

  •  1
  • Brian Millot  · 技术社区  · 4 年前

    我正在尝试构建一个简单的启动和停止计时器功能,但是当我再次单击该功能时,clearInterval似乎没有任何效果。事实上,计时器不会停止。然而,我可以启动它,但我不能关闭它。

    const [seconds, setSeconds] = useState(0);
    const [timer, setTimer] = useState();
    
    const handleStartToggle = (seconds) => {
      // Start new timer only if it's not run yet
      if(!timer) {
        setTimer(setInterval(() => {
          setSeconds((current) => current + 1);
        }, 1000));
      // Else, it's already running, we stop it
      } else {
        return () => clearInterval(timer);
      }
    }
    
    <div className="row project-task-showcase">
      <h2 className="client-name"> {activeClient.name}</h2>
      <p className="task-name">{activeTask.name}</p>
      <img src={play} className="play" onClick={handleStartToggle} />
      {seconds}
    </div>
    
    1 回复  |  直到 4 年前
        1
  •  3
  •   RiTeSh    4 年前

    作为回报, 你作为函数返回,所以在函数中它不起作用,

    将代码更改为

    const handleStartToggle = (seconds) => {
      // Start new timer only if it's not run yet
      if(!timer) {
        setTimer(setInterval(() => {
          setSeconds((current) => current + 1);
        }, 1000));
      // Else, it's already running, we stop it
      } else {
        clearInterval(timer);   // <-- Change here
       // setTimer(null); // <-- To toggle next time 
      }
    }
    
        2
  •  1
  •   Varun Naharia David van Driessche    4 年前

    在您的 handleStartToggle 您正在为其执行不同工作的功能 if else 陈述对于 如果 您执行的语句很少,但 其他的 返回的箭头函数不正确。要更正此问题,必须在两个

    const handleStartToggle = (seconds) => {
    // Start new timer only if it's not run yet
    if(!timer) {
       return () => {setTimer(setInterval(() => {
         setSeconds((current) => current + 1);
       }, 1000));
     }
    // Else, it's already running, we stop it
    } else {
      return () => clearInterval(timer);
     }
    }
    <div className="row project-task-showcase">
    <h2 className="client-name"> {activeClient.name}</h2>
    <p className="task-name">{activeTask.name}</p>
    <img src={play} className="play" onClick={()=> handleStartToggle()} />
    {seconds}
    </div>
    

    或在两者中都使用语句

    const handleStartToggle = (seconds) => {
    // Start new timer only if it's not run yet
    if(!timer) {
      setTimer(setInterval(() => {
        setSeconds((current) => current + 1);
      }, 1000));
    // Else, it's already running, we stop it
    } else {
      clearInterval(timer);   // <-- Change here
      setTimer(null); // <-- To toggle next time 
    }
    

    }