Skip to content

Instantly share code, notes, and snippets.

@DesignHhuang
Created September 28, 2023 10:51
Show Gist options
  • Save DesignHhuang/7499a8d6d42695782c6df7d06364118a to your computer and use it in GitHub Desktop.
Save DesignHhuang/7499a8d6d42695782c6df7d06364118a to your computer and use it in GitHub Desktop.
useTimer hook
import { ref, onUnmounted } from 'vue';
export const useTimer = (callback = () => { }, step = 1000) => {
let timerVariableId = null;
let times = 0;
const isPaused = ref(false);
const stop = () => {
if (timerVariableId) {
clearInterval(timerVariableId);
timerVariableId = null;
resume();
}
}
const start = () => {
stop();
if (!timerVariableId) {
times = 0;
timerVariableId = setInterval(() => {
if (!isPaused.value) {
times++;
callback(times, step * times);
}
}, step)
}
}
const pause = () => {
isPaused.value = true;
}
const resume = () => {
isPaused.value = false;
}
onUnmounted(() => {
if (timerVariableId) {
clearInterval(timerVariableId);
}
})
return {
start,
stop,
pause,
resume,
isPaused
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment