调用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)
    }
相关推荐
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-04-05
前端·数据库·人工智能·经验分享·神经网络
SuperEugene2 小时前
Vue3 组件复用设计:Props / 插槽 / 组合式函数,三种复用方式选型|组件化设计基础篇
前端·javascript·vue.js
nFBD29OFC2 小时前
利用Vue元素指令自动合并tailwind类名
前端·javascript·vue.js
ISkp3V8b42 小时前
ASP.NET MVC]Contact Manager开发之旅之迭代2 - 修改样式,美化应用
前端·chrome
Highcharts.js3 小时前
高级可视化图表的暗色模式与主题|Highcharts 自适应主题配色全解
前端·react.js·实时图表
zk_one4 小时前
【无标题】
开发语言·前端·javascript
AIBox3655 小时前
openclaw api 配置排查与接入指南:网关启动、配置文件和模型接入全流程
javascript·人工智能·gpt
precious。。。5 小时前
1.2.1 三角不等式演示
前端·javascript·html
阿珊和她的猫5 小时前
TypeScript 中的 `extends` 条件类型:定义与应用
javascript·typescript·状态模式
众创岛5 小时前
iframe的属性获取
开发语言·javascript·ecmascript