Recently delved into Vue and JS. I've implemented a watcher for a timerCount
variable (initialized to 5) that triggers a 5-second timer. When the variable reaches zero, certain code is executed, and then I reset the timer to 5 to start over. Everything works as expected, but when a click event invokes a method which executes different code and resets the timer to 5, the timer speeds up (twice as fast).
After doing some research online, it seems like there are multiple instances of watchers/timers running simultaneously, causing the acceleration. How can I resolve this issue so my method simply resets the timer normally?
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 now it runs twice as fast, unsure why.
otherMethod(){
/* Code */
this.timerCount=5
}
}
Any suggestions on how to solve this dilemma?
Referenced source: How do I create a simple 10 seconds countdown in Vue.js