视频直播系统源码,react-hooks的页面设置定时器

视频直播系统源码,react-hooks的页面设置定时器

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

 

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

以上就是 视频直播系统源码,react-hooks的页面设置定时器,更多内容欢迎关注之后的文章

 

posted @   云豹科技-苏凌霄  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示