我正在玩 VueJS 并创建了一个简单的计数器。我想重置 resetTimer()
函数中的 setInterval()
方法。但是,它不起作用。不确定我在这里遗漏了什么。
new Vue({
el: '#app',
data: {
hours: 0,
minutes: 0,
seconds: 0,
counter: 0
},
methods: {
timer() {
setInterval(() => {
this.seconds = this.timerFormat(++this.counter % 60)
this.minutes = this.timerFormat(parseInt(this.counter / 60, 10) % 60)
this.hours = this.timerFormat(parseInt(this.counter / 3600, 10))
}, 1000);
},
resetTimer() {
clearInterval(this.timer())
},
timerFormat(timer) {
return timer > 9 ? timer : '0' + timer;
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lean Vue</title>
</head>
<body>
<div id="app">
<p>{{ hours }} : {{ minutes }} : {{ seconds }}</p>
<button @click="timer">Start</button>
<button @click="resetTimer">Pause</button>
</div>
<script src="dist/bundle.js"></script>
</body>
</html>
最佳答案
为间隔计时器定义一个全局变量(在我的示例中为 my_timer
),然后您可以在重置操作中清除它:
new Vue({
el: '#app',
data: {
hours: 0,
minutes: 0,
seconds: 0,
counter: 0,
my_timer :0
},
methods: {
timer() {
this.my_timer = setInterval(() => {
this.seconds = this.timerFormat(++this.counter % 60)
this.minutes = this.timerFormat(parseInt(this.counter / 60, 10) % 60)
this.hours = this.timerFormat(parseInt(this.counter / 3600, 10))
}, 1000);
},
pauseTimer() {
clearInterval(this.my_timer)
},
timerFormat(timer) {
return timer > 9 ? timer : '0' + timer;
}
}
})
希望这对您有所帮助。
new Vue({
el: '#app',
data: {
hours: 0,
minutes: 0,
seconds: 0,
counter: 0,
my_timer:0
},
methods: {
timer() {
this.my_timer = setInterval(() => {
this.seconds = this.timerFormat(++this.counter % 60)
this.minutes = this.timerFormat(parseInt(this.counter / 60, 10) % 60)
this.hours = this.timerFormat(parseInt(this.counter / 3600, 10))
}, 1000);
},
resetTimer() {
clearInterval(this.my_timer)
this.hour=0
this.minutes=0
this.seconds=0
this.counter=0
},
timerFormat(timer) {
return timer > 9 ? timer : '0' + timer;
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lean Vue</title>
</head>
<body>
<div id="app">
<p>{{ hours }} : {{ minutes }} : {{ seconds }}</p>
<button @click="timer">Start</button>
<button @click="resetTimer">Reset</button>
</div>
<script src="dist/bundle.js"></script>
</body>
</html>
关于javascript - 从对象重置 setInterval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41259457/