how to set timeout in a vueJs method

JavascriptPhpJqueryLaravel 5vue.js

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

setTimeout(()=>{
   this.yourMethod()
},1000);

> An arrow function does not have its own this. The this value of > the enclosing lexical scope is used;

Arrow functions - JavaScript | MDN

Solution 3 - Javascript

Try this: setTimeout(this.fetchHole, 1000) because this in anonymous function is attached to that anonymous function not to your main function

Solution 4 - Javascript

I think this works too.

var self = this;
setTimeout(function () { self.fetchHole() } , 1000)

Solution 5 - Javascript

Call recursive with TimeOut:

    save: function () {
      this.progressToProced = 0
      this.progress()          
    },
    progress: function () {
      if (this.progressToProced < 100) {
        this.progressToProced++
        setTimeout(function () { this.progress() }.bind(this), 100)
      }
    }

Solution 6 - Javascript

You can try :

addHole:function(){
  let vm = this
  setTimeout(function(){vm.fetchHole()}, 1000)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3757488View Question on Stackoverflow
Solution 1 - JavascriptceejayozView Answer on Stackoverflow
Solution 2 - JavascriptDeivizView Answer on Stackoverflow
Solution 3 - JavascriptnosporView Answer on Stackoverflow
Solution 4 - JavascriptRubens BarbosaView Answer on Stackoverflow
Solution 5 - JavascriptDarlan DieterichView Answer on Stackoverflow
Solution 6 - JavascriptGamitha AnjanaView Answer on Stackoverflow