[Vuejs]-Vue countdown timer infinite loop

0๐Ÿ‘

var application = new Vue({
  template: '<div>{{ remaining.days }} days, {{ remaining.hours }} hours, {{ remaining.minutes }} mins, {{ remaining.seconds }} sec</div>',
  data:
    {
      counter: 0,
      countdown: new Date('2019-12-17T03:24:00Z')
    },
    created: function()
    {
      this.advance();
    },
    methods:
    {
      advance: function()
      {
        setTimeout(this.timer, 1000);
      },
      timer: function()
      {
        this.counter++;
        this.advance();
      }
    },
    computed:
    {
      remaining: function()
      {
        var tmp = this.counter + 1; // we just want to invalidate the cached computed value and thus trigger re-rendering of the template
        var timeDiff = this.countdown.getTime() - Date.now();
        return {
          days: Math.floor(timeDiff / (1000 * 60 * 60 * 24)),
          hours: Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
          minutes: Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((timeDiff % (1000 * 60)) / 1000),
        }
      }  
    },
    }).$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Leave a comment