创建倒计时器时,IF Else 语句在 setInterval() 函数中无法正常工作

问题描述 投票:0回答:1

即使在 setInterval() 函数中添加 if else 语句以在时间变量达到 0 时清除间隔,setInterval() 仍然以负时间值运行。

这是我的倒计时器组件代码:

import { useEffect, useState, useRef } from "react";

export const Timer = () => {
  const [time, setTime] = useState(10000);
  const [pause, setPause] = useState(false);
  let timerRef = useRef(null);

  useEffect(() => {  
    console.log("run")
    startTimer();
  
    return () => clearInterval(timerRef.current);
  }, []);

  const stopTimer = () => {
    clearInterval(timerRef.current);
    setPause(true);
  };

  const startTimer = () => {
    setPause(false);
    timerRef.current = setInterval(() => {
      if (time <= 0) {
        console.log("checked");
        clearInterval(timerRef.current);
        setPause(true);
      }
      else{
        setTime((prevTime) => prevTime - 1000);
      }
    }, 1000);

  };

  const getFormattedText = (time) => {
    const SECONDS = 1000;
    const MINUTES = 60 * SECONDS;
    const HOURS = 60 * MINUTES;
    const DAYS = 24 * HOURS;

    const days = Math.floor(time / DAYS);
    const hours = Math.floor((time % DAYS) / HOURS);
    const minutes = Math.floor((time % HOURS) / MINUTES);
    const seconds = Math.floor((time % MINUTES) / SECONDS);

    return (
      <div className="countdown-timer">
        {days < 10 ? `0${days}` : days} : {hours < 10 ? `0${hours}` : hours} :{" "}
        {minutes < 10 ? `0${minutes}` : minutes} :{" "}
        {seconds < 10 ? `0${seconds}` : seconds}
      </div>
    );
  };
  return (
    <>
      {getFormattedText(time)}
      <div>
        <button onClick={pause ? startTimer : stopTimer}>
          {!pause ? "Stop" : "Start"} Timer
        </button>
      </div>
    </>
  );
};

export default Timer;

这是 0 秒后的输出:

enter image description here

javascript reactjs settimeout setinterval
1个回答
0
投票

您点击事件可能会自动触发

<button onClick={() => {pause ? startTimer : stopTimer}}>
© www.soinside.com 2019 - 2024. All rights reserved.