[Vuejs]-How to update Time in DOM In Vue.js without uisng set-timeout or set-interval

0👍

For things that need to change after a single update cycle we have this.$nextTick. This is, however, not really useful for a timer. That makes window.setInterval the next best thing.

Keep in mind that just like with manually added event handlers, timeouts and intervals must be manually cleared in a lifecycle hook. Your current code should be something like:

new Vue({
  el: '#app',
  data: {
    seconds: (new Date).getSeconds(),

    intervalRef: null
  },
  mounted () {
    this.intervalRef = window.setInterval(() => {
      this.seconds = (new Date).getSeconds();
    });
  },
  beforeDestroy () {
    if (this.intervalRef) {
      window.clearInterval(this.intervalRef);
      this.intervalRef = null;
    }
  }
});

Leave a comment