Created
May 14, 2019 23:00
-
-
Save pklink/a3df25b1ff6800ecc82ea489792f00d3 to your computer and use it in GitHub Desktop.
reactive stop watch based on vue
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
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 | |
//> ... |
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
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