Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent timer from lagging behind #41

Merged
merged 1 commit into from
May 18, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions src/renderer/utils/timer.js
Original file line number Diff line number Diff line change
@@ -8,27 +8,41 @@ export default class {

start() {
if (!this.timerInt) {
this.timerInt = setInterval(() => {
// we are not calling back on fixed seconds, but on fixed seconds plus this offset
const msOffset = new Date().getMilliseconds()

const timerLoop = () => {
this.time += 1
if (this.time >= this.totalSeconds) {
this.pause()
EventBus.$emit('timer-completed')
// return to prevent the next timeout
return
} else {
EventBus.$emit('timer-advanced', this.time, this.totalSeconds)
}
}, 1000)

// compute how many ms to wait before the next call
// we do this because the callback takes time, so calling with 1000 ms of delay each time
// makes us lag behind after a bit
const computedTimeout = 1000 - (new Date().getMilliseconds() - msOffset)
this.timerInt = setTimeout(timerLoop, computedTimeout)
}

// first call is always in 1000 ms
this.timerInt = setTimeout(timerLoop, 1000)
EventBus.$emit('timer-started')
}
}

pause() {
clearInterval(this.timerInt)
clearTimeout(this.timerInt)
delete this.timerInt
EventBus.$emit('timer-paused')
}

reset() {
clearInterval(this.timerInt)
clearTimeout(this.timerInt)
delete this.timerInt
this.time = 0
EventBus.$emit('timer-reset')