-1

I want backAgain to be executed 2 secs after clicking button stopCrash but console is returning error: Uncaught TypeError: this.backAgain is not a function

any ideas?

methods:{
    backAgain(){
      this.winning = 0;
      this.betAmount = 0;
      this.moneyValue = null;
    },
    cashOut(){
      clearTimeout(this.tessst);
      this.money = Number(this.money) + Number(this.winning);
      setTimeout(function(){
        this.backAgain()
      },2000)
    }}
<button class="stopCrash" @click="cashOut">Cash out</button>
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
aravinvafshe
  • 277
  • 1
  • 5
  • 12

4 Answers4

1

You should use an arrow function in order to access this context :

  cashOut(){
      clearTimeout(this.tessst);
      this.money = Number(this.money) + Number(this.winning);
      setTimeout(()=>{
        this.backAgain()
      },2000)
    }}
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
1

It's all because you're loosing this when you set a timeout, because function(){} doesn't save the this context, but as arrow functions do, check the difference between them

setTimeout(() => this.backAgain(), 2000)
Max
  • 1,996
  • 1
  • 10
  • 16
1

You need to bind this. Arrow function does it for you. If you are using IE 11 and you don't have arrow functions, you can bind in this way:

setTimeout(function(){ this.backAgain() }.bind(this), 2000)

In your case, you can bind and execute with call or apply execute:

setTimeout(this.backAgain.call(this), 2000)
Ziv Ben-Or
  • 1,149
  • 6
  • 15
1

this is lost when the callback is called, but you can for example use a local variable in its closure (the usual concept of accessing variables from "outer" blocks surrounding a piece of code extended with the "twist" that the variables can be accessed even after the immediate code which contained them has finished running), which is not lost:

cashOut(){
  clearTimeout(this.tessst);
  this.money = Number(this.money) + Number(this.winning);
  var diz = this;             // <--- store
  setTimeout(function(){
    diz.backAgain();          // <--- use
  },2000)
}}
tevemadar
  • 12,389
  • 3
  • 21
  • 49