setTimeout() not working called from vueJS method setTimeout() not working called from vueJS method vue.js vue.js

setTimeout() not working called from vueJS method


The value of this is different inside the setTimeout.

If you're using ES6, you can use an arrow function:

setTimeout(() => { this.message = this.server + ': Reset' }, 2000)

Or if you're not, you can bind the value of this:

setTimeout(function () {  this.message = this.server + ': Reset'}.bind(this))

However, having never used Vue, I don't know if it will know to re-render when you change the value of this.message, or if you should be changing some component state or something.


Because you're inside a setTimeout, this doesn't correspond with your Vue instance. You can use self instead :

systemReset: function(){    this.message = this.server + ': Resetting';    var self = this;    setTimeout(function(){        self.message = self.server + ': Reset';    }, 2000);}


Could be solved of storing this in a variable out of the timeout function?

Like so:

 systemReset: function(){            var $this = this;            $this.message = this.server + ': Resetting';            setTimeout(function(){                $this.message = this.server + ': Reset';            }, 2000);         }

Doing so refers to the correct function systemReset