I am currently attempting to create a timer using vue.js, but I am encountering some issues with my methods section:
methods: {
saveRunningMethod() {
var runningData = {
duration: `${this.hour} : ${this.minute} : ${this.second}`,
username: this.$store.state.user.username
}
this.$store.dispatch('saveRunning' , runningData)
console.log(runningData);
},
startTimer(){
this.isTimerStart = true;
var timer = window.setInterval(() => {
var e = document.getElementById("stopBtn")
e.addEventListener("click", function(){
clearInterval(timer)
this.isTimerStart = false;
console.log("lets Save it")
this.saveRunningMethod()
});
if(this.mSecond < 9)
this.mSecond +=1
else
this.mSecond=0
if(this.mSecond==9)
this.second +=1
if(this.second>59)
this.second=0
if(this.second==59)
this.minute +=1
if(this.minute>59)
this.minute=0
if(this.minute==59)
this.hour+=1
},100);
}
}
In the code above,
e.addEventListener("click", function(){
is used to stop the timer when clicking on the 'stop' button. However, this method seems to be running multiple times and resulting in multiple executions of console.log as depicted in this image: https://i.sstatic.net/z5vLR.jpg
Another issue I am facing is with the line: this.saveRunningMethod()
. When I try to call this method within my startTimer()
method, I receive an error stating "this.saveRunningMethod() is not a function."
Finally, for the timer setup utilizing setInterval
, if you have any suggestions for a more efficient solution, your input would be greatly appreciated.
UPDATE: Including my HTML component below:
<div class="row p-2 m-3 mt-3">
<div class="col-12 p-0 animated fadeInUp mt-3">
<p class="text-center">Your last record was : 00:00:00</p>
</div>
<div class="col-12 p-0 animated fadeInUp mt-3">
<h1 class="text-center timer">
{{this.hour}}:{{this.minute}}:{{second}}:{{mSecond}}
</h1>
</div>
</div>
<div class="row p-2 mt-3" v-bind:class="[this.isTimerStart==false ? 'show' : 'hide']">
<div class="col-12 p-0 animated tada text-center">
<button class="btn-link timerImg" @click="startTimer()">
<img class="img-fluid timerImg" src="../../static/timerStart.png" />
<p>Start</p>
</button>
</div>
</div>
<div class="row p-2 mt-3" v-bind:class="[this.isTimerStart ? 'show' : 'hide']">
<div class="col-12 p-0 animated tada text-center">
<button id="stopBtn" class="btn-link timerImg">
<img class="img-fluid timerImg" src="../../static/timerStop.png" />
<p>Stop</p>
</button>
</div>
</div>
Thank you for your assistance.