I have a countdown function in vue.js that updates too fast.
Here is the data section
data() {
return {
selected: [],
countdown: timerLimit
}
Below is the countdown method
countdownTimer() {
this.countdown = 60;
var downloadTimer = setInterval(() => {
if(this.countdown <= 0){
clearInterval(downloadTimer);
if (this.thisUser.captain) {
Store.submitTurnEnd();
}
}
this.countdown -= 1
console.log(this.countdown)
}, 1000);
},
Which gets called above. However, I notice after clicking a few times, it often goes too fast. I think I need to update the data section but am unsure how to.
Thanks for the help.
It could help you whit another variable in data:
data() {
return {
selected: [],
countdown: timerLimit,
isCountdownActive: false
}
Method:
countdownTimer() {
// exit method if it is active
if(this.isCountdownActive == true) return;
// first time set ttrue
this.isCountdownActive = true
this.countdown = 60;
var downloadTimer = setInterval(() => {
if(this.countdown <= 0){
clearInterval(downloadTimer);
if (this.thisUser.captain) {
Store.submitTurnEnd();
}
// On exit interval, restart to false
this.isCountdownActive = false
}
this.countdown -= 1
console.log(this.countdown)
}, 1000);
},
You can try this.
new Vue({
el: "#app",
data: {
counter: 5
},
methods: {
countdownTimer: function() {
let interval;
interval = setInterval(() => {
if (this.counter > 0) {
this.counter = this.counter - 1;
} else {
clearInterval(interval);
// Do whatever you want to do
}
}, 1000);
}
}
})
And the template part is
<div id="app">
<h2>Countdown:</h2>
<h1>{{ counter }}</h1>
<button v-on:click="countdownTimer">Start</button>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.