-1

im learning vue and setInterval doesn't work like in normal javascript? the problem is that my update function doesn't get fired. start gets fired from a button, and hours/minutes/seconds are bound to input fields with v-model, i get all console.logs before the setInterval.

export default Vue.extend({
  name: "timer-c",

  data() {
    return {
      startDate: undefined,
      hours: "",
      minutes: "",
      seconds: "",
      timeLeft: undefined,
      endDate: undefined,
      interval: undefined,
      text: "00:00:00",
      sub: undefined,
    };
  },

  methods: {
    start: function() {
      if (this.sub === undefined) {
        let sum = 0;
        if (this.seconds.match(/^\d+$/)) {
          sum = sum + this.seconds * 1000;
          console.log(sum);
        }
        if (this.minutes.match(/^\d+$/)) {
          sum = sum + this.minutes * 60 * 1000;
        }
        if (this.hours.match(/^\d+$/)) {
          sum = sum + this.hours * 60 * 60 * 1000;
        }
        if (sum === 0) {
          console.log(this.$refs.br_start);
          this.failed = true;
        } else {
          console.log(sum);
          this.failed = false;
          this.endDate = new Date(Date.now() + sum);
          console.log(this.endDate);
          this.startDate = new Date(Date.now());
          console.log(this.startDate);
          this.interval = setInterval(time => this.update, 1000);
          //this.sub = this.interval.subscribe(time => this.update(time));
        }
      }
    },
    update: function() {
      console.log('test');
      const timeRemaining = Math.round((Date.now() - this.endDate) / 1000);
      this.text = timeRemaining;
      if (new Date(Date.now()) >= this.endDate) {
        console.log("test");
      }
    },
Syler
  • 220
  • 7
  • 17

1 Answers1

1

Try to not return the function but execute it

this.interval = setInterval(time => { this.update(time) }, 1000);
Daniel Kemeny
  • 640
  • 1
  • 5
  • 11
  • thanks now it works but has a delay before starting. – Syler Apr 21 '19 at 08:49
  • You can find an answer to this problem here : https://stackoverflow.com/questions/6685396/execute-the-setinterval-function-without-delay-the-first-time – BTL Apr 21 '19 at 09:06
  • Then you can execute this.update(time) before the interval to have an immediate execution – Daniel Kemeny Apr 21 '19 at 09:27