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
The classic issue with contextual
this
in JavaScript.The following part of code shows an easy solution - if you are using ES6 with Vuejs (default config with vuecli y babel). Use an arrow function
I think this works too.
Call recursive with TimeOut:
Try this:
setTimeout(this.fetchHole, 1000)
becausethis
in anonymous function is attached to that anonymous function not to your main functionAdd a
bind()
call to your function declaration: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.