0

When I console.log(this.showBox) within the setTimeout(), the console.log() returns undefined, which is different from the false that I was expecting. May I know if the setTimeout() makes the this.keyword unaccessible? Thanks!

<script>
import Block from "./components/Block.vue"
export default {
  name: 'App',
  components: {
    Block,
  },
  data() {
    return {
      isPlaying: false,
      delay: null,
      timer: null,
      reactionTime: 0,
      showBox:false,

    }
  },
  methods: {
    startGame() {
      this.isPlaying = true;
      //this.delay = 2000 + Math.floor(Math.random(1,4000) * 4000)
      this.delay = 1000
      console.log(this.delay)
      console.log(this.showBox)

      setTimeout(function() {
        console.log(this.showBox)
      }, this.delay);
    },
  },
}
</script>
deekeh
  • 675
  • 1
  • 6
  • 21
tan shi yu
  • 303
  • 1
  • 7
  • 2
    you need to know how `this` works in javascript - there's much information just on stack overflow about it - hint, instead of `function() {` do `() => {` in the setTimeout – Jaromanda X May 23 '21 at 07:52
  • another way to do it is just to pass the data variable into setTimeout function. https://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback – Dorvalla May 23 '21 at 07:58
  • @JaromandaX Hello, thank you very much for this explanation! It works with () => now but I will definitely go check out the resources on the differences between the stuff you mentioned! Again, thank you very much! – tan shi yu May 23 '21 at 07:59

3 Answers3

0

Although there's a correct answer, I still wanna write down an answer as a note that setTimeout & setInterval will creates its own context both so that variable this can't not be realized.

newbie
  • 66
  • 2
  • Hello, yeah I think so as well. However, when using the ( )=> instead of function( ) { }, I managed to use the this and access the showBox. I think it might have something to do with how this we declare our functions as well. Anyways thanks for the help! – tan shi yu May 23 '21 at 08:12
0

Arrow function works but there is another way you can achieve this. Read about call, bind and apply methods.

Your problem can be solved in following way using bind method.
Note: What bind does is it creates a new function and sets this to passed value. Refer: MDN bind() method docs for more info.

setTimeout(function() {
   console.log(this.showBox)
}.bind(this), this.delay);
-2

When using this in setTimeout, it creates its own context and hence it's become undefined, you can use arrow function to share the same context.

setTimeout(() => {
        console.log(this.showBox)
      }, this.delay);
Yash Maheshwari
  • 1,842
  • 2
  • 7
  • 16
  • Hello, thank you, this answer does workout! You are correct that it creates it's own context and therefore I could utilize this keyword. I will go and learn the differences between the 2 soon. Thanks again! – tan shi yu May 23 '21 at 08:00