Last active
October 17, 2018 13:47
-
-
Save HazelGrant/62fc3b2de647d23eaf3e59c23a03825d to your computer and use it in GitHub Desktop.
ES6 Vue Stopwatch Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<div id='stopwatch'> | |
{{ displayHours }}:{{ displayMinutes }}:{{ displaySeconds }} | |
</div> | |
<button @click="start">Start</button> | |
<button @click="stop">Stop</button> | |
<button @click="clear">Clear</button> | |
</div> | |
</template> | |
<script> | |
// Revision notes: second/minute/hour calculations got messed up | |
// because this.milliseconds needs to only keep track of how much | |
// unpaused time has passed since startTime, and that was causing | |
// this.seconds/this.minutes/this.hours to completely miscalculate | |
// after the one minute mark. Calculating seconds/minutes/hours on | |
// the fly based on milliseconds prevents this from happening. | |
// I don't know if this.seconds is better as a computed property | |
// or as a method. The caching of computed properties is probably | |
// really unnecessary for seconds, more so for minutes, and most | |
// of all for hours. So... | |
export default { | |
name: 'stopwatch', | |
data() { | |
return { | |
milliseconds: 0, | |
startTime: null, | |
timer: null | |
} | |
}, | |
computed: { | |
seconds() { | |
return Math.floor(this.milliseconds / 1000) | |
}, | |
displaySeconds() { | |
return this.padZero(this.seconds % 60) | |
}, | |
minutes() { | |
return Math.floor(this.seconds / 60) | |
}, | |
displayMinutes() { | |
return this.padZero(this.minutes % 60) | |
}, | |
hours() { | |
return Math.floor(this.minutes / 60) | |
}, | |
displayHours() { | |
return this.padZero(this.hours) | |
} | |
}, | |
methods: { | |
start() { | |
// Start now, or, if we've paused previously, now, but accounting for the previous milliseconds | |
this.startTime = Date.now() - this.milliseconds | |
// Check time since startTime every 100 milliseconds | |
this.timer = setInterval(this.add, 100) | |
}, | |
add() { | |
this.milliseconds = Date.now() - this.startTime | |
}, | |
stop() { | |
// Need to leave this.milliseconds alone so we can start again later | |
clearInterval(this.timer) | |
}, | |
clear() { | |
stop() | |
// If the timer is still running, resetting this.startTime puts us back at zero without having to rerun this.start() | |
this.startTime = Date.now() | |
this.milliseconds = 0 | |
}, | |
padZero(value) { | |
return value >= 10 ? value : '0' + value | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment