How to use setTimeout in Vue JS?

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.

Jasminkumar Borad
Jasminkumar Borad

I'm a full-stack developer, enterpreneur and owner of webstuffsolution.com. I live in india and i like to write tutorial and tips that can help to other user. I like to share various programming language tips and solution. I believe in hardworking and consistency.

Leave a Reply

Your email address will not be published. Required fields are marked *