Search code examples
javascriptvue.jscountdown

vuejs timer component restart/stop


i have to setup a 10 min timer which redirects to homescreen. Furthermore it have to reset on every action (e.g. button press). I found this timer: https://github.com/fengyuanchen/vue-countdown is it possible to restart it on a action?

<countdown ref="countdown" @end="dosmth()" :time="time" :auto-start="false">
<template slot-scope="props">{{ props.seconds }}</template>
</countdown>

mounted() {
    this.$refs.countdown.start();
  },


dosmth: function(){
          this.$refs.countdown.start();
        }

This should restart the timer but even this wont work:

Basket.vue:378 [Vue warn]: Error in event handler for "end": "InternalError: too much recursion"

Maybe someone can help me out?


Solution

  • You can do this with setInterval and resetting the value to the initial value on each action click:

    const TEN_MINUTES = 60 * 10
    
    new Vue({
      el: '#app',
      data () {
        return {
          timer: TEN_MINUTES
        }
      },
      filters: {
        minutesAndSeconds (value) {
          var minutes = Math.floor(parseInt(value, 10) / 60)
          var seconds = parseInt(value, 10) - minutes * 60
          return `${minutes}:${seconds}`
        }
      },
      mounted () {
        setInterval(() => {
          this.timer -= 1
        }, 1000)
      },
      methods: {
        someAction () {
          this.timer = TEN_MINUTES
        },
        someOtherAction () {
          this.timer = TEN_MINUTES
        }
      },
      template: `<div><div>Time Remaining: {{ timer | minutesAndSeconds }}</div><br><br><button @click="someAction">Some Action</button><button @click="someOtherAction">Some Other Action</button></div>`
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"></div>