[英]Why does my countdown function run to quickly?
我在 vue.js 中有一个倒计时 function 更新太快。
这是数据部分
data() {
return {
selected: [],
countdown: timerLimit
}
下面是倒计时方法
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);
},
上面调用了哪个。 但是,我注意到点击几次后,它经常走得太快。 我想我需要更新数据部分,但不确定如何更新。
谢谢您的帮助。
它可以帮助您使用数据中的另一个变量:
data() {
return {
selected: [],
countdown: timerLimit,
isCountdownActive: false
}
方法:
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);
},
你可以试试这个。
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);
}
}
})
模板部分是
<div id="app">
<h2>Countdown:</h2>
<h1>{{ counter }}</h1>
<button v-on:click="countdownTimer">Start</button>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.