Skip to content

Commit

Permalink
refactor: 使用 Web Worker 定时器
Browse files Browse the repository at this point in the history
  • Loading branch information
orilights committed May 26, 2024
1 parent 427cc5d commit 6a7296b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@
<SettingItem title="CPU图表">
<Switch v-model="settings.showCpuChart" />
</SettingItem>
<SettingItem v-show="settings.showCpuChart" title="记录时间">
<select v-model="settings.cpuChartHistoryKeep">
<option value="60">
1分钟
</option>
<option value="180">
3分钟
</option>
<option value="300">
5分钟
</option>
<option value="600">
10分钟
</option>
</select>
</SettingItem>
</div>
</div>
</Transition>
Expand Down Expand Up @@ -102,7 +118,6 @@ import type { ServerData } from './types'
const JSON_API = '/json/stats.json'
const CARD_WIDTH = 350
const REFRESH_INTERVAL = 500
const MIN_FETCH_INTERVAL = 500
const { width: WindowWidth } = useWindowSize()
Expand All @@ -111,6 +126,7 @@ const settings = useLocalStorage('sstl-settings', {
layout: 'grid',
compactMode: false,
showCpuChart: false,
cpuChartHistoryKeep: 300,
}, {
mergeDefaults: true,
})
Expand All @@ -124,6 +140,7 @@ const error = ref(false)
const fetching = ref(false)
const showSettingPanel = ref(false)
const latestUpdated = ref(0)
const timer = ref<Worker>()
const serverCardCount = computed(() => {
return Math.floor(WindowWidth.value / CARD_WIDTH) || 1
Expand All @@ -138,9 +155,11 @@ onMounted(() => {
.then(res => res.json())
.then((data) => {
serverData.value = data
setInterval(() => {
timer.value = new Worker(new URL('./worker/timer.js', import.meta.url))
timer.value.addEventListener('message', () => {
fetchData()
}, REFRESH_INTERVAL)
})
timer.value.postMessage('start')
})
.catch(() => {
error.value = true
Expand All @@ -150,6 +169,11 @@ onMounted(() => {
})
})
onUnmounted(() => {
if (timer.value)
timer.value.postMessage('stop')
})
function fetchData() {
if (fetching.value)
return
Expand Down
13 changes: 13 additions & 0 deletions src/worker/timer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
let timer = null

onmessage = (e) => {
if (e.data === 'start') {
timer = setInterval(() => {
postMessage('tick')
}, 500)
}
if (e.data === 'stop') {
clearInterval(timer)
timer = null
}
}

0 comments on commit 6a7296b

Please sign in to comment.