清除间隔在VUE中不起作用

问题描述 投票:0回答:2

我正在尝试使用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);
          }
        },

You can find a live demo here.

在页面中,当我单击开始时,将调用设置的Interval方法。然后我点击停止,它应该清除间隔,但它似乎不起作用,因为我打算。您可以检查控制台并轻松找到“123”不断弹出,表示间隔未清除。

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

我们将非常感谢您的帮助。提前致谢!

javascript jquery vue.js
2个回答
3
投票

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

只需使用this.interval,变量将添加到组件的数据部分。

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


2
投票

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

if (val && !this.t) {
    this.t = setInterval(() => {
        location.reload()
    }, 10 * 1000)
} else {
    clearInterval(this.t)
}
© www.soinside.com 2019 - 2024. All rights reserved.