Last active
April 30, 2021 13:05
-
-
Save motatoes/45e815ff0c83d95710557fdf85af0b8c to your computer and use it in GitHub Desktop.
quick and dirty stopwatch component for vueJS
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> | |
<span id="time" v-html="time"></span> | |
</template> | |
<style> | |
</style> | |
<script> | |
module.exports = { | |
data: function() { | |
return { | |
state: "started", | |
startTime: Date.now(), | |
currentTime: Date.now(), | |
interval: null | |
} | |
}, | |
mounted: function() { | |
this.interval = setInterval(this.updateCurrentTime, 1000); | |
}, | |
destroyed: function() { | |
clearInterval(this.interval) | |
}, | |
computed: { | |
time: function() { | |
return this.hours + ':' + this.minutes + ':' + this.seconds; | |
}, | |
milliseconds: function() { | |
return this.currentTime - this.$data.startTime; | |
}, | |
hours: function() { | |
var lapsed = this.milliseconds; | |
var hrs = Math.floor((lapsed / 1000 / 60 / 60)); | |
return hrs >= 10 ? hrs : '0' + hrs; | |
}, | |
minutes: function() { | |
var lapsed = this.milliseconds; | |
var min = Math.floor((lapsed / 1000 / 60) % 60); | |
return min >= 10 ? min : '0' + min; | |
}, | |
seconds: function() { | |
var lapsed = this.milliseconds; | |
var sec = Math.ceil((lapsed / 1000) % 60); | |
return sec >= 10 ? sec : '0' + sec; | |
} | |
}, | |
methods: { | |
reset: function() { | |
this.$data.state = "started"; | |
this.$data.startTime = Date.now(); | |
this.$data.currentTime = Date.now(); | |
}, | |
pause: function() { | |
this.$data.state = "paused"; | |
}, | |
resume: function() { | |
this.$data.state = "started"; | |
}, | |
updateCurrentTime: function() { | |
if (this.$data.state == "started") { | |
this.currentTime = Date.now(); | |
} | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Whenever you start the stopwatch it starts with one second when it should start with 0 seconds, why is this?
EDIT:
Solved this by editing the function
seconds
:But I'm not sure if it's a good practice