In this tutorial i will show you how to use setTimeout in Vue js. This post will help you to call setTimeout using mounted().
We can simply use setTimeout() in core jquery for some repeat task on specific time. I call function from mounted() in Vue.js. Below is an example and explanation of how to use it effectively in Vue.js
1. Change message after a Specific time using setTimeout in Vue js
Here’s simple Vue.js example where a message updates after a 3-second using setTimeout.
Example
<template>
<div>
<p> {{message}} </p>
<button @click="changeMessage"></button>
</div>
</template>
<script>
export default {
data() {
return {
message: "Hello, welcome to Vue.js post",
};
},
methods: {
changeMessage() {
setTimeout(() =>{
this.message = "Hi, User You are working fine!"
}, 3000);
},
},
mounted() {
this.changeMessage();
}
};
</script>
Explanation:
- message: Stores the initial message displayed in the template.
- Displays the current message and includes a button trigger changeMessage method.
- changeMessage: Uses setTimeout to update the message property after 3 seconds.
- mounted lifecycle hook runs the component is mounted in the DOM.
I hope this tutorial help you.