Skip to content

Instantly share code, notes, and snippets.

@pklink
Created May 14, 2019 23:00
Show Gist options
  • Save pklink/a3df25b1ff6800ecc82ea489792f00d3 to your computer and use it in GitHub Desktop.
Save pklink/a3df25b1ff6800ecc82ea489792f00d3 to your computer and use it in GitHub Desktop.
reactive stop watch based on vue
import stopwatch from 'vue-stopwatch'
stopwatch.$watch('seconds', console.log)
stopwatch.start()
//> 1
//> 2
//> 3
stopwatch.pause()
//>
stopwatch.resume()
//> 4
//> 5
stopwatch.stop()
//>
stopwatch.start()
//> 1
//> 2
//> ...
import Vue from 'vue'
let ival, lastTs
export default new Vue({
computed: {
seconds () {
return Math.round(this.milliseconds / 1000)
}
},
data: {
milliseconds: 0
},
methods: {
pause () {
clearInterval(ival)
},
resume () {
this.start()
},
start () {
lastTs = Date.now()
ival = setInterval(() => {
// get current timestamp
const currentTs = Date.now()
// get difference between now and last check
const diff = currentTs - lastTs
// add difference to total running time
this.milliseconds += diff
// save current timestamp for next iteration
lastTs = currentTs
}, 100)
},
stop () {
this.milliseconds = 0
clearInterval(ival)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment