Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Vue to count up by seconds

I'm creating a small timer Vue component. A user needs to be able to start and stop that timer. Here's my component thus far:

<template>
    <div>
        <a class="u-link-white" href="#" @click="toggleTimer">
            {{ time }}
        </a>
    </div>
</template>

<script>
    export default {
        props: ['order'],
        data() {
            return {
                time: this.order.time_to_complete,
                isRunning: false,
            }
        },
        methods: {
            toggleTimer() {
                var interval = setInterval(this.incrementTime, 1000);
                if (this.isRunning) {
                    //debugger
                    clearInterval(interval);
                    console.log('timer stops');
                } else {
                    console.log('timer starts');
                }
                this.isRunning = (this.isRunning ? false : true);
            },
            incrementTime() {
                this.time = parseInt(this.time) + 1;
            },
        }
    }
</script>

I'm toggling the isRunning variable to determine whether the timer is running or not. On first click (the play), the timer begins and increments successfully.

However, on the second click (the pause), the isRunning var toggles back to off, but clearInterval(this.incrementTime) is not clearing the interval and pausing the timer. When I insert that debugger, and manually hit clearInterval(interval) via the console, it returns undefined.

Does anybody have any insight on how I've formatted my component incorrectly?

like image 896
Cameron Scott Avatar asked Dec 22 '17 16:12

Cameron Scott


1 Answers

Here is a working example covering the concepts I mentioned in the comment above. This is not an exact implementation of your component, just an example to show you how it could work.

console.clear()
new Vue({
  el: "div",
  data() {
    return {
      time: 0,
      isRunning: false,
      interval: null
    }
  },
  methods: {
    toggleTimer() {
      if (this.isRunning) {
        clearInterval(this.interval);
        console.log('timer stops');
      } else {
        this.interval = setInterval(this.incrementTime, 1000);
      }
      this.isRunning = !this.isRunning
    },
    incrementTime() {
      this.time = parseInt(this.time) + 1;
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div>
  <a class="u-link-white" href="#" @click="toggleTimer">
    {{ time }}
   </a>
</div>
like image 95
Bert Avatar answered Oct 23 '22 21:10

Bert