How to use setTimeout with Vue | Equivalent of setTimeout() function.
Find out how to use setTimeout() function in Vue js application.
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:
<a href="https://codesandbox.io/s/dazzling-wozniak-zy7ksn?fontsize=14&hidenavigation=1&theme=dark"> <img alt="Edit zy7ksn" src="https://codesandbox.io/static/img/play-codesandbox.svg"> </a>Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
