2

very new to Vue and JS. I've setup a watcher for a timerCount variable (initially set to 5) which makes a 5 second timer. When the variable hits 0, some code is executed, and I reset the timer to 5 to restart it. This works perfectly fine, however, I have a click event which calls a method, which will execute different code and then reset the timer to 5 as well, but now my timer is accelerated (twice as fast).

From what I could find from googling, it seems that there are multiple watcher/timer instances running at the same time, which is what causes the speed up. How do I fix this so my method simply reset the timer like normal?

watch: {
    timerCount: {
        handler(value){
            //timer for 5 seconds
            if (value>0){
                setTimeout(() => {
                    this.timerCount--;
                }, 1000);
            }
            //if timer hits 0, execute code and reset timerCount to 5 seconds, this works fine
            else{
                /* Code */
                this.timerCount=5
            }
        },
        immediate: true,
    }
},

methods:{
    //this resets the timer, but it now goes twice as fast, don't know why.
    otherMethod(){
        /* Code */
        this.timerCount=5
    }

}

Any help?

Here is the post where I got this code: How do I create a simple 10 seconds countdown in Vue.js

mmvahora
  • 103
  • 1
  • 6

2 Answers2

0

In you code, you are watching timerCount. When you make a change on your timeCount means, when you run otherMethod, Vue watches it then run watcher again and handler for this watcher runs again. Everytime you change timerCount variable your watcher run and again and again.

Actually without watcher you can start your time inside your created event with setInterval (not setTimeout). setInterval run your code within givin interval but not strictly 1000ms. It may be 1005ms or less.

You can create some function inside setInterval and give it like 100ms and control the time if it is passed 5 seconds or not.

gguney
  • 2,512
  • 1
  • 12
  • 26
0

Create a method (createWatcher()) that initializes a watcher and saves the watcher instance as a data variable. Call the createWatcher() when the component is created and each time you need to modify the watched variable, stop the watcher and update the variable then create the watcher again. (see whenUpdatingVariable())

Refer to creating watcher and stopping watcher

data(){
 return{
  myWatcherInstance: null,
  timerCount: 10
 }
}
methods: {
 whenUpdatingVariable(){
  // stop watcher/unwatch
  this.myWatcherInstance();

  // update variable
  this.timerCount = 20;

  // create watcher again
  this.createWatcher();
 },
 createWatcher(){
    this.myWatcherInstance = this.$watch('timerCount', () => {
        setTimeout(() => {
          this.timerCount--;
        }, 1000);
      })
    }
  }
},
created(){
 this.createWatcher();
}
Derrick
  • 11
  • 3