-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeWorker.js
104 lines (90 loc) · 2.52 KB
/
timeWorker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
let targetEndTime = null;
let updateInterval = null;
let backgroundTimeout = null;
let isInBackground = false;
// 處理前景更新
function handleForegroundUpdate() {
if (updateInterval) {
clearInterval(updateInterval);
}
updateInterval = setInterval(() => {
sendTimeUpdate();
}, 1000);
}
// 處理背景更新
function handleBackgroundUpdate() {
// 清除前景的 interval
if (updateInterval) {
clearInterval(updateInterval);
updateInterval = null;
}
const now = Date.now();
const remainingTime = targetEndTime - now;
if (remainingTime > 0) {
// 設置一次性 timeout 到結束時間
backgroundTimeout = setTimeout(() => {
sendTimeUpdate();
self.postMessage({ command: 'end' });
}, remainingTime);
}
}
// 發送時間更新
function sendTimeUpdate() {
if (!targetEndTime) return;
const now = Date.now();
const remainingTime = Math.max(0, targetEndTime - now);
if (remainingTime > 0) {
self.postMessage({
command: 'tick',
remainingTime: remainingTime
});
} else {
// 清理所有計時器
cleanup();
self.postMessage({ command: 'end' });
}
}
// 清理函數
function cleanup() {
if (updateInterval) {
clearInterval(updateInterval);
updateInterval = null;
}
if (backgroundTimeout) {
clearTimeout(backgroundTimeout);
backgroundTimeout = null;
}
}
self.onmessage = function(event) {
const { command, time, isBackground } = event.data;
switch (command) {
case 'start':
cleanup();
targetEndTime = Date.now() + time;
isInBackground = isBackground;
if (isBackground) {
handleBackgroundUpdate();
} else {
handleForegroundUpdate();
}
// 立即發送第一次更新
sendTimeUpdate();
break;
case 'stop':
cleanup();
targetEndTime = null;
break;
case 'visibility-change':
isInBackground = isBackground;
if (targetEndTime) {
if (isBackground) {
handleBackgroundUpdate();
} else {
handleForegroundUpdate();
}
// 切換時立即更新一次
sendTimeUpdate();
}
break;
}
};