[Vuejs]-Should I use setInterval() in a watcher?

0👍

I think that the problem is that this inside of the setInterval ‘this’ doesn’t reference anymore to vue instance.

To solve this problem I’d try something like creating a const to hold the ‘this’ that references to vue instance.

The code could be like this!

watch: {
time() {
  const vueThis = this;
  setInterval(
    () => {
      if (vueThis.time >= vueThis.maxTimes) {
        vueThis.isUpdating = false;
      }
      vueThis.time = vueThis.animate
        ? Math.min(vueThis.time + 1, vueThis.maxTimes)
        : vueThis.maxTimes;
    },
    vueThis.isUpdating ? DELAY_IN_MS : null
  );
},

},

I hope that it can help you!!

Leave a comment