Skip to content

Commit

Permalink
fix: can not stop calling the 'update' method when elapsed > duration…
Browse files Browse the repository at this point in the history
…, in the timer example. #2359 (#2360)
  • Loading branch information
wangzhilongh committed May 19, 2023
1 parent f618a3a commit 1a50977
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 20 deletions.
34 changes: 24 additions & 10 deletions src/examples/src/timer/App/composition.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,41 @@
import { ref, onUnmounted } from 'vue'

import { ref, onUnmounted, computed } from 'vue'
export default {
setup() {
const duration = ref(15 * 1000)
const elapsed = ref(0)

let lastTime = performance.now()
let lastTime
let handle

const update = () => {
const time = performance.now()
elapsed.value += Math.min(time - lastTime, duration.value - elapsed.value)
lastTime = time
handle = requestAnimationFrame(update)
elapsed.value = performance.now() - lastTime
if (elapsed.value >= duration.value) {
cancelAnimationFrame(handle)
} else {
handle = requestAnimationFrame(update)
}
}

const reset = () => {
elapsed.value = 0
lastTime = performance.now()
update()
}

update()
const progressRate = computed(() =>
Math.min(elapsed.value / duration.value, 1)
)

reset()

onUnmounted(() => {
cancelAnimationFrame(handle)
})

return {
duration,
elapsed
elapsed,
progressRate,
reset
}
}
}
29 changes: 21 additions & 8 deletions src/examples/src/timer/App/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,29 @@ export default {
}
},
created() {
let lastTime = performance.now()
const update = () => {
const time = performance.now()
this.elapsed += Math.min(time - lastTime, this.duration - this.elapsed)
lastTime = time
this.handle = requestAnimationFrame(update)
}
update()
this.reset()
},
unmounted() {
cancelAnimationFrame(this.handle)
},
computed: {
progressRate() {
return Math.min(this.elapsed / this.duration, 1)
}
},
methods: {
update() {
this.elapsed = performance.now() - this.lastTime
if (this.elapsed >= this.duration) {
cancelAnimationFrame(this.handle)
} else {
this.handle = requestAnimationFrame(this.update)
}
},
reset() {
this.elapsed = 0
this.lastTime = performance.now()
this.update()
}
}
}
4 changes: 2 additions & 2 deletions src/examples/src/timer/App/template.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<label
>Elapsed Time: <progress :value="elapsed / duration"></progress
>Elapsed Time: <progress :value="progressRate"></progress
></label>

<div>{{ (elapsed / 1000).toFixed(1) }}s</div>
Expand All @@ -9,4 +9,4 @@
{{ (duration / 1000).toFixed(1) }}s
</div>

<button @click="elapsed = 0">Reset</button>
<button @click="reset">Reset</button>

0 comments on commit 1a50977

Please sign in to comment.