调用clearInterval(), 定时器仍在进行

背景

我是在 react 的函数组件中遇到这个问题的,

出现问题的代码片段:

js 复制代码
const SelfDevProgress = (props)=> {
    const [getChangePer,setGetChangePer] = useState(percent)

    let timer = null; // 定时器
    
    // 调起进度条
    const initial = () => {
        // 进度条步数
        let per = 0
        setGetChangePer(per)
        timer = setInterval(() => {          
            per += s
            if(per === 99) { // 在100之前要卡住停顿
                clearInterval(timer)
            }
            if(per + s >= 100) { // 最后一段改变步幅
                s = 1
            }
            setGetChangePer(per)
        }, 100);
    }
    
    // 响应失败
    const fail = () => {
        // 清除定时器
        clearInterval(timer) // 这里调用clearInterval了,但是定时器仍在运行
    }

}

在 fail() 函数中调用 clearInterval 来清除定时器了, 但是发现定时器还在运行.

解决办法

把 timer 改成 useState 那种方式就可以了.

js 复制代码
    const [timer,setTimer] = useState(null) // 定时器

    // 调起进度条
    const initial = async () => {
        // 进度条步数
        let per = 0
        setGetChangePer(per)
        let t = setInterval(() => {          
            per += s
            if(per === 99) { // 在100之前要卡住停顿
                clearInterval(t)
            }
            if(per + s >= 100) { // 最后一段改变步幅
                s = 1
            }
            setGetChangePer(per)
        }, 100);
        setTimer(t)
    }
相关推荐
aiguangyuan25 分钟前
React 18 源码解读(一)
javascript·react·前端开发
LFly_ice30 分钟前
学习React-23-React-router
前端·学习·react.js
haofafa40 分钟前
JavaScript性能优化实战
开发语言·javascript·性能优化
我叫张小白。1 小时前
TypeScript对象类型与接口:构建复杂数据结构
前端·javascript·typescript
O***p6041 小时前
JavaScript增强现实开发
开发语言·javascript·ar
墨客希1 小时前
如何快速掌握大型Vue项目
前端·javascript·vue.js
大福ya1 小时前
AI开源项目改造NextChat(ChatGPT-Next-Web)实现前端SSR改造打造一个初始框架
前端·chatgpt·前端框架·开源·aigc·reactjs·ai编程
samroom1 小时前
langchain+ollama+Next.js实现AI对话聊天框
javascript·人工智能·langchain
n***33351 小时前
SpringBoot返回文件让前端下载的几种方式
前端·spring boot·后端
纯粹的热爱2 小时前
🌐 阿里云 Linux 服务器 Let's Encrypt 免费 SSL 证书完整部署指南
前端