I'm building a basic Timer Vue component. The timer increments by seconds, and the user can play and pause the timer on click. Here's the component:
<template>
<div v-bind:class="{workspaceTimer: isRunning}">
<a class="u-link-white" href="#" @click="toggleTimer">
{{ time }}
<span v-if="isRunning">
Pause
</span>
<span v-else>
Play
</span>
</a>
</div>
</template>
<script>
export default {
props: ['order'],
data() {
return {
time: this.order.time_to_complete,
isRunning: false,
interval: null,
}
},
watch: {
time: function (newTime) {
this.saveTime()
}
},
methods: {
toggleTimer() {
if (this.isRunning) {
clearInterval(this.interval);
} else {
this.interval = setInterval(this.incrementTime, 1000);
}
this.isRunning = !this.isRunning;
},
incrementTime() {
this.time = parseInt(this.time) + 1;
},
formattedTime() {
var sec_integer = parseInt(this.time, 10);
var hours = Math.floor(sec_integer / 3600);
var minutes = Math.floor((sec_integer - (hours * 3600)) / 60);
var seconds = sec_integer - (hours * 3600) - (minutes * 60);
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
this.time = +minutes+':'+seconds;
},
saveTime: _.debounce(
function () {
var self = this;
axios.put(location.pathname, {time_to_complete: self.time})
.then(function (response) {
console.log('timer: ' + response.data.time_to_complete);
})
.catch(function (error) {
console.log('Error: ' + error);
})
},
1000
)
}
</script>
I'm storying the second count as an integer, but would like to display that second count as a mm:ss, and have that formatted value increment, e.g. 00:59 increments to 1:00.
I can easily format my second value using a method or computed property (see the formattedTime() method in that example), but I'm unsure of how to approach incrementing that string, and then formatting that incremented string. Do I need to watch for changes to that string, and then format the updated string?
timeshould be an integer counting seconds.formattedTimeshould be acomputed- Roy J