How to use setTimeout with Vue | Equivalent of setTimeout() function.

featured Image

In this short post, we will see how to use the setTimeout() function in Vue Js.

The setTimeout() function method executes a function or a block of code after a specific time.

Syntax:

setTimeout(function, milliseconds);

Here, 1000 miliseconds = 1second

The setTimeout is useful to run a function after a specified time delay or sometimes we can use it to emulate a server request for some demos.

Now let’s see how we can use the setTimeout() in a Vue method to change the text of a variable.

<template>
  <div id="app">
    <button @click="changeText()">Change Text</button>
    <h1>{{ text }}</h1>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      text: "Hello World",
    };
  },
  methods: {
    changeText() {
      setTimeout(() => {
        this.text = "Welcome World";
      }, 2000);
    },
  },
};
</script>

Here, we have a function changeText(), which have a setTimeout() function that change the text after 2 seconds.

So now when we click the button, it executes the changeText() method, and the this.text changes to ‘Welcome World‘ after a delay of 2 seconds.

Code Demo:

Edit zy7ksn

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

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