You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对象中定义setInterval后无法调用clearInterval清除定时器问题

问题根因

  • 核心错误是drawCircle函数的else分支中,调用清除定时器的方法时没有加执行括号:你写的this.clear只是引用了函数对象,并没有实际执行函数逻辑,所以定时器永远不会被清除。
  • 补充注意点:初始化时values[0][0]为undefined,虽然当前逻辑是赋值后再启动定时器不会触发异常,但建议初始化时给默认值避免后续扩展出现问题。

修复方案

只需要把else分支里的this.clear改成this.clear()即可触发定时器清除逻辑,修复后的完整代码如下:

let values = [[]]
let Circle_1 = {
  procent: values[0][0],
  startFrom: 0,
  incrementBy: 0,
  start: null,
  intervalIdAtStart: function(){
    this.start = setInterval(function(){
      drawCircle.call(Circle_1)
    },500)
  },
  clear: function() {
    clearInterval(this.start);
  }
}

function drawCircle(inputValues){  
    if(this.startFrom < this.procent){
        console.log('draw <', this.procent + "     " + this.startFrom)
        this.startFrom++
    }
    else if(this.startFrom > this.procent){
        console.log('draw >', this.procent + "     " + this.startFrom)
        this.startFrom--
    }
    else{
        console.log('else', this.procent + "     " + this.startFrom)
        // 新增括号执行clear方法
        this.clear();
    }
};

function Http(){
    let output = 100
    loadoutput(output)

    function loadoutput(input){
        console.log(input)
        values = [
            [input], 
        ]
        Circle_1.procent = values[0][0]
        Circle_1.intervalIdAtStart()
    }
}

function getValues(){
  Http();
}

setTimeout(getValues,1000);

内容的提问来源于stack exchange,提问作者ukulele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:36:05