[Vuejs]-Vue screen that refreshes periodically, done safely

1👍

This approach together with try-catch is a way to go, have a look at this snippet:
https://codepen.io/alexbrohshtut/pen/YzXjNeB

<div id="app">
  <wrapper/>
</div>
Vue.component("interval-component", {
  template: `
    <div>  {{lastRefreshed}}
      <button @click="init">Start</button></div>`,
  data() {
    return {
      timeoutId: undefined,
      lastRefreshed: undefined
    };
  },
  methods: {
    doJob() {
      if (Math.random() > 0.9) throw new Error();
      this.lastRefreshed = new Date();
      console.log("Job done");
    },
    init() {
      if (this.timeoutId) return;
      this.run();
    },
    run() {
      console.log("cycle started");
      const vm = this;
      this.timeoutId = setTimeout(function() {
        try {
          vm.doJob();
        } catch (e) {
          console.log(e);
        } finally {
          vm.run();
        }
      }, 2000);
    }
  },
  destroyed() {
    clearTimeout(this.timeoutId);
    console.log("Destroyed");
  }
});
Vue.component("wrapper", {
  template: `<div>  <button @click="create" v-if="destroyed"> Create</button>
    <button v-else @click="destroy">Destroy</button>

    <interval-component v-if="!destroyed" /></div>`,
  data() {
    return {
      destroyed: true
    };
  },
  methods: {
    destroy() {
      this.destroyed = true;
    },
    create() {
      this.destroyed = false;
    }
  }
});
new Vue({
  el: "#app"
});

Leave a comment