react-hooks的页面设置定时器

hooks页面设置定时器

在hooks中设置定时器时,设置变量储存定时器时最后用:const [timer, setTimer] = useState(null); 这样方式存储,否则会导致在使用完定时器,清除定时器,无法清除干净,定时器仍然还在,(特别是页面定时器)

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

const ChallengeModal = (props) => {
  const [timesContent, setTimesContent] = useState("");
  const [timer, setTimer] = useState(null);
 
  const handleCancelStatus = (e) => {
    clearInterval(timer);
  };
 
  const setTime = (val) => {
    let times = val;
    let h = 0,
      m = 0,
      s = 0;
    if (times > 0) {
      h = Math.floor(times / 60);
      m = Math.floor(times) - h * 60;
      s = Math.floor(times * 60) - m * 60;
    }
    if (h <= 9) h = "0" + h;
    if (m <= 9) m = "0" + m;
    if (s <= 9) s = "0" + s;
    if (s === 0) s = "00";
    setTimesContent(h + ":" + m + ":" + s);
  };

  // 造计时器
  const makeTime = () => {
    let  limit_time  =60;
    let times = limit_time * 60;
    // let timer = null;
    const MeTimer = setInterval(() => {
      let h = 0,
        m = 0,
        s = 0;
      if (times > 0) {
        h = Math.floor(times / (60 * 60));
        m = Math.floor(times / 60) - h * 60;
        s = Math.floor(times) - h * 60 * 60 - m * 60;
      }
      if (h <= 9) h = "0" + h;
      if (m <= 9) m = "0" + m;
      if (s <= 9) s = "0" + s;
      setTimesContent(h + ":" + m + ":" + s);
      times--;
      if (times < 0) {
        console.log("122");
        clearInterval(timer);
      }
    }, 1000);
    setTimer(MeTimer);
    console.log("times", times);
   };
   const closeTime =()=>{
  	 clearInterval(timer);
      setTimer(null);
   }
   useEffect(() => {
    setTime(timer)
   }, []);
  return (
    <div>
     <button onClick={()=>makeTime()}>打开</button>
     {timesContent}
     <button onClick={()=>closeTime()}>关闭</button>
    </div>
  );
};
export default ChallengeModal;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值