W
W
Wolfcrusher2019-03-24 18:35:25
JavaScript
Wolfcrusher, 2019-03-24 18:35:25

How to correctly use a timer as a Vue method (problem when accessing this)?

Dear experts, the situation is as follows: I wrote a code in Vue for a timer that should display a countdown on the screen and change the route at zero.
The problem is that my understanding of the use of this is very limited, and I can't figure out how to reactively change the outer counter of the timer method from the counter function ( f ). Besides, I can't figure out how to make $router work from function f. Perhaps a different approach should be used?
Thank you in advance.

export default {
  data() {
  	return { counter: 10 }
  },
  methods: {
  timer(counter) {
      let f = function(counter) {
      	if (counter>0) {
      	  console.log(counter);
          counter--;
      	  setTimeout((f.bind(null,counter)), 1000);
        } else (this.$router.push({ path: '/2'}));
      }
      f(counter);
    } 
  },
  mounted() {
    this.timer(this.counter);
  } 
}

Thanks for the replies, everything works.
In the process, another question arose: when manually changing the route in the browser line, the application starts to "fail" - change the route spontaneously at some points when counter > 0. The application itself works in a loop with changing several similar routes. Hence the question - how to make it so that when manually changing the route, the application starts its work correctly, as if from a "clean slate" of the corresponding route. I think there is some kind of snag in the hooks, maybe mounted () is not suitable, but with others, the situation turned out no better for me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex, 2019-03-24
@Wolfcrusher

export default {
  data() {
    return {
      counter: 10
    }
  },
  methods: {
    countDown() {
      if (this.counter) {
        return setTimeout(() => {
          --this.counter
          this.countDown()
        }, 1000)
      }

      this.$router.push({ path: '/2'})
    }
  },
  mounted() {
    this.countDown();
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question