调用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)
    }
相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby8 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing8 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩8 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车9 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
Front思9 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫11 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。12 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星12 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒13 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端