清除间隔在 VUE 中不起作用

Leo*_* Ge 2 javascript jquery vue.js

我正在尝试使用 VUE.js 构建一个番茄钟定时器,下面是我遇到问题的相关代码片段。所以问题是 clearInterval 方法在这里似乎不起作用。

   data: {
        workTimeInMin: 1,
        breakTimeInMin: 1,
        timeRemainInMillisecond: 0,
        timerOn: false,
        rest: false
      },

      methods: {
        startOrStopTheTimer: function() {
          var self = this;
          var interval;
          if (this.timerOn){
            this.timerOn = !this.timerOn;
            window.clearInterval(interval);
            console.log("clearInterval");
          }else {
            this.timerOn = !this.timerOn;
            interval = setInterval(function(){
            console.log("123");
            if (self.timeRemainInMillisecond <= 0) {
              console.log("1");
              self.rest = !self.rest;
              if (self.rest) {
                self.timeRemainInMillisecond = self.restTimeInMin*60*1000;
              }else {
                self.timeRemainInMillisecond = self.workTimeInMin*60*1000;
              }
            }
              this.timeRemainInMillisecond = this.timeRemainInMillisecond-1000
            }, 1000);
          }
        },
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到现场演示。

在页面中,当我单击开始时,会调用 set Interval 方法。然后我点击了停止,它应该清除间隔,但是它似乎并没有像我想要的那样工作。您可以检查控制台并轻松发现“123”不断弹出,这表明间隔未清除。

在 StackOverFlow 中搜索了一段时间后,我发现如果我interval在全局上下文中定义变量,它将按我的预期工作。但我想知道为什么会这样。

您的帮助将不胜感激。提前致谢!

Rei*_*ner 7

你的问题是var interval每次调用函数时都是一个声明的新函数。因此,无法访问保存对您的间隔的引用的变量。

只需使用this.interval,该变量就会添加到组件的后台数据部分。

你也可以只使用这个 mixin(插件)/看看它是如何工作的: Vue interval mixin

  • 这在 2019 年 12 月对我有用 - 我没有在“data() { }”部分中声明间隔,而是只是将我的间隔分配给 this.interval。将其添加到数据中使其无法工作。 (2认同)

Riz*_*izo 6

您可以清除 setInterval 和 clearinterval。这是示例代码,请根据您的需要进行修改

if (val && !this.t) {
    this.t = setInterval(() => {
        location.reload()
    }, 10 * 1000)
} else {
    clearInterval(this.t)
}
Run Code Online (Sandbox Code Playgroud)