调用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)
    }
相关推荐
FRing035 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
Bczheng15 小时前
组件化服务端渲染模式SSR
前端
whitelbwwww6 小时前
CUDA C++实战--中级
开发语言·前端·c++
张紫娃7 小时前
Chrome插件-Stylus(屏蔽博客广告)
前端·chrome·stylus
Yannik7 小时前
在 Apple Silicon Mac 上用 Jenkins + Fastlane 搭建 iOS CI:从自动打包到 MR 检查流水线的完整实践
前端
Nayana7 小时前
《Web 到 HarmonyOS》-- 打包:Vite 产物 → HAP / HAR / HSP
前端
inksci7 小时前
用飞帆做了个小网页
前端·javascript·css·html
去伪存真7 小时前
被 pnpm 打包坑惨后,我彻底盘明白了硬链接与软链接
前端·electron
zhensherlock8 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
多加点辣也没关系11 小时前
JavaScript|第40章:JavaScript 工程化实践
开发语言·javascript·ecmascript