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!
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With