Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set timeout in a vueJs method

how I can use settimeout() function in a vuejs method?

I have already tried something like this, but it doesn't work

fetchHole: function () {      //get data },  addHole: function () {     //my query add new     setTimeout(function () { this.fetchHole() }, 1000) }, 

I get this Error message : Uncaught TypeError: this.fetchHole is not a function

like image 571
user3757488 Avatar asked May 26 '16 15:05

user3757488


People also ask

How do I create a timeout in JavaScript?

The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);

How do you write if condition in Vue?

v-else-if directive is a Vue. js directive used to toggle the display CSS property of an element depending on a condition when the if condition is not satisfied. First, we will create a div element with id as app and let's apply the v-else-if directive to an element with data.

What is Set time Out function?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

How do I clear set timeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.


1 Answers

Add a bind() call to your function declaration:

setTimeout(function () { this.fetchHole() }.bind(this), 1000) 

so that your Vue component's this is accessible within the function.

Side note: @nospor's accepted answer is cleaner in this particular situation. The bind approach is a bit more generalized - very useful if you want to do an anonymous function, for example.

like image 70
ceejayoz Avatar answered Sep 22 '22 00:09

ceejayoz