Sometimes, we want to create a simple 10 seconds countdown in Vue.js.
In this article, we’ll look at how to create a simple 10 seconds countdown in Vue.js.
How to create a simple 10 seconds countdown in Vue.js?
To create a simple 10 seconds countdown in Vue.js, we can use the setInterval
function.
For instance, we write:
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id='app'>
</div>
to add the Vue script and the app container.
Then we write:
const v = new Vue({
el: '#app',
template: `<p>{{timerCount}}</p>`,
data: {
timerCount: 10
},
mounted() {
const timer = setInterval(() => {
this.timerCount--;
if (this.timerCount === 0) {
clearInterval(timer)
}
}, 1000);
}
})
We call setInterval
with a callback to decrement this.timerCount
every second until it reaches 0.
When it reaches 0, then we call clearInterval
with timer
to clear the timer.
We call setInterval
in the mounted
hook to start the timer when the component is mounted.
Counclsion
To create a simple 10 seconds countdown in Vue.js, we can use the setInterval
function.