Skip to content

Instantly share code, notes, and snippets.

@motatoes
Last active April 30, 2021 13:05
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save motatoes/45e815ff0c83d95710557fdf85af0b8c to your computer and use it in GitHub Desktop.
Save motatoes/45e815ff0c83d95710557fdf85af0b8c to your computer and use it in GitHub Desktop.
quick and dirty stopwatch component for vueJS
<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>
@superpep
Copy link

superpep commented Apr 30, 2021

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:

seconds: function () {
      const lapsed = this.milliseconds
      const sec = Math.ceil((lapsed / 1000) % 60)
      return sec >= 10 ? sec : '0' + (sec === 0 ? sec : sec - 1)
    }

But I'm not sure if it's a good practice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment