Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Interval doesn't work in VUE

I am trying to build a Pomodoro Timer using VUE.js, below is the relevant code snippet that I had problems on. So the problem is that the clearInterval Method doesn't seem to work here.

   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.

In the page, when I click start an set Interval method is called. Then I clicked the stop, it is supposed to clear the interval, however it doesn't seem to work as I intend it to. You can inspect the console and easily find the "123" keeps popping up which indicates that the interval is not cleared.

After searching a while in the StackOverFlow, I found that if I define the variable interval to in the global context it will work as I intend it. But I wish to know why it is so.

Your help will be highly appreciated. Thanks in advance!

like image 412
Leonard Ge Avatar asked Mar 04 '26 19:03

Leonard Ge


2 Answers

Your problem is that var interval is a declared new every time the function is called. So the variable that holds a reference to your interval is not accessible.

Just use this.interval and the variable will added to the data-section of your component under the hood.

You can also just use this mixin (plugin) / have a look how it works there: Vue interval mixin

like image 167
Reiner Avatar answered Mar 06 '26 09:03

Reiner


You can clear setInterval and clearinterval. here is sample code please modify according to your need

if (val && !this.t) {
    this.t = setInterval(() => {
        location.reload()
    }, 10 * 1000)
} else {
    clearInterval(this.t)
}
like image 40
Rizwan Avatar answered Mar 06 '26 09:03

Rizwan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!