Vue Setinterval and Clearinterval

In this tutorial, we will learn how to use setInterval and clearInterval with Vue.js. These functions are crucial for executing code at specified intervals. With these functions, we can perform a variety of tasks such as animation and fetching data periodically.

written

reviewed

updated

Thanks for your feedback!
Your contributions will help us to improve service.
How to use setInterval in the vue component?
The example below demonstrates the use of setInterval() in Vue.js to change the time every 5 seconds.
Example of using setInterval() in Vue Js
Copied to Clipboard
x
<div id="app">
<p>{{message}}</p>
</div>
<script type="module">
import { createApp } from "vue";
createApp({
data() {
return {
message: '',
}
},
mounted() {
setInterval(() => {
return this.message = new Date().toLocaleTimeString();
}, 5000)
},
}).mount("#app");
</script>
Output of above example
How to stop setinterval in Vue?
In the example below, we demonstrate how to clear an interval in Vue js to stop timers or execute code at regular intervals.
Vue Clear Interval Example
Copied to Clipboard
xxxxxxxxxx
<script type="module">
import {createApp} from "vue";
createApp({
data() {
return {
counter: 0,
intervalId: null // To hold the interval ID
};
},
methods: {
startCounter() {
this.intervalId = setInterval(() => {
this.counter++;
}, 1000);
},
stopCounter() {
clearInterval(this.intervalId);
}
},
beforeUnmount() {
clearInterval(this.intervalId);
}
}).mount("#app");
</script>
Output of Vue Stop Setinterval
Ad