How do I create a simple 10 seconds countdown in Vue.js
Whilst the accepted answer works, and is great, it can actually be achieved in a slightly simpler way by utilising Vue.js watchers:
<template>
{{ timerCount }}
</template>
<script>
export default {
data() {
return {
timerCount: 30
}
},
watch: {
timerCount: {
handler(value) {
if (value > 0) {
setTimeout(() => {
this.timerCount--;
}, 1000);
}
},
immediate: true // This ensures the watcher is triggered upon creation
}
}
}
</script>
The benefit of using this method is that the timer can be immediately reset by simply setting the value of timerCount
.
If you would like to play/pause the timer, then you can achieve this like so (note - this is not a perfect solution as it will round to the nearest second):
<template>
{{ timerCount }}
</template>
<script>
export default {
data() {
return {
timerEnabled: true,
timerCount: 30
}
},
watch: {
timerEnabled(value) {
if (value) {
setTimeout(() => {
this.timerCount--;
}, 1000);
}
},
timerCount: {
handler(value) {
if (value > 0 && this.timerEnabled) {
setTimeout(() => {
this.timerCount--;
}, 1000);
}
},
immediate: true // This ensures the watcher is triggered upon creation
}
}
methods: {
play() {
this.timerEnabled = true;
},
pause() {
this.timerEnabled = false;
}
}
}
</script>
Please check if this works for you.
<template>
{{ countDown }}
</template>
<script>
export default {
data () {
return {
countDown: 10
}
},
methods: {
countDownTimer () {
if (this.countDown > 0) {
setTimeout(() => {
this.countDown -= 1
this.countDownTimer()
}, 1000)
}
}
},
created () {
this.countDownTimer()
}
}
</script>