setTimeout behaviour in vuejs

Viewed 27

As you can see below the timer is supposed to update the msg after 90s have been elapsed but it does it rather instantly. I am aware of setInterval and watch but I need to know why does the code wont work

All we doing is checking the counter is above 0 if so spawn yet another timeout and in that trigger this current function and so on

var view = new Vue({
  el: '#app',
  data: {
    countDown: 90,
    msg: "There's still time.."
  },
  methods: {
    timer: function () {
      if (this.countDown > 0) {
        setTimeout(() => {
          this.countDown--
          this.timer()
        }, 1000);
      }
      else if(this.countDown === 0);
      {
        this.msg = 'You Ran Outta Time!'
      }
    }
  },
  
  created () {
    this.timer();
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Vue test</title>
</head>
<body>
  <div id="app">
    <h2>{{msg}}</h2>
  </div> 
</body>
</html>

1 Answers

Remove the ; after else if(this.countDown === 0) which is considered as statement, so your code is the same as :

  if (this.countDown > 0) {
            setTimeout(() => {
              this.countDown--
              console.log(this.countDown)
              this.timer()
            }, 1000);
          }
          else if(this.countDown === 0)
          {
                      
          }
   this.msg = 'You Ran Outta Time!'

var view = new Vue({
  el: '#app',
  data: {
    countDown: 90,
    msg: "There's still time.."
  },
  methods: {
    timer: function () {
      if (this.countDown > 0) {
        setTimeout(() => {
          this.countDown--
          console.log(this.countDown)
          this.timer()
        }, 1000);
      }
      else if(this.countDown === 0)
      {
      
        this.msg = 'You Ran Outta Time!'
      }
    }
  },
  
  created () {
    this.timer();
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Vue test</title>
</head>
<body>
  <div id="app">
    <h2>{{msg}}</h2>
  </div> 
</body>
</html>

Related