## 效果如上
<!-- 將 main.js 和 worker.js 放在同一個目錄下,然后在 HTML 文件中引入 main.js --><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Web Worker 倒計時</title>
</head>
<body><h1>Web Worker 倒計時示例</h1><p>打開控制臺查看倒計時日志。</p><script src="main.js"></script>
</body>
</html>
// main.js
//主線程負責啟動 Web Worker,并接收 Web Worker 發送的消息(例如倒計時的剩余時間)。
function padZero(num) {if (num < 10) {return '0' + num;}return String(num);
}
// 創建一個新的 Web Worker
const worker = new Worker('worker.js');// 向 Worker 發送消息,啟動倒計時
worker.postMessage({ action: 'start', duration: 60 }); // 60秒倒計時// 監聽 Worker 發送的消息
worker.onmessage = function (event) {const duration = event.data.timeLeft;if (duration <= 0) {console.log('倒計時結束!');} else {const hours = Math.floor(duration / (60 * 60))const remainMin = duration % (60 * 60)const mins = Math.floor(remainMin / 60)const sec = remainMin % 60const showTime=`${padZero(hours)}:${padZero(mins)}:${padZero(sec)}`console.log('剩余時間:', showTime);}
};// 如果需要停止倒計時,可以發送停止消息
// worker.postMessage({ action: 'stop' });
// worker.js 負責執行倒計時邏輯,并將剩余時間發送回主線程let timer = null;// 監聽主線程發送的消息
self.onmessage = function (event) {const { action, duration } = event.data;if (action === 'start') {// 記錄倒計時開始的時間let startTime = duration;// 使用 setInterval 每秒更新一次剩余時間timer = setInterval(() => {const elapsed = Date.now() - startTime; // 已過去的時間const timeLeft = startTime -1; // 剩余時間startTime=timeLeftif (timeLeft <= 0) {clearInterval(timer); // 清除定時器self.postMessage({ timeLeft: 0 }); // 通知主線程倒計時結束} else {self.postMessage({ timeLeft }); // 發送剩余時間給主線程}}, 1000); // 每秒更新一次} else if (action === 'stop') {// 如果收到停止消息,清除定時器clearInterval(timer);}
};
vue的實現
// // 將 worker.js 轉換為 Blob URL// const blob = new Blob([workerCode], { type: 'application/javascript' });// const workerURL = URL.createObjectURL(blob);// // 初始化 Web Worker// this.worker = new Worker(workerURL);// // 監聽 Web Worker 發送的消息// this.worker.onmessage = (event) => {// const timeLeft = event.data.timeLeft;// this.duration=timeLeft// if (timeLeft <= 0) {// this.setTime()// this.back("0")// } else {// this.setTime()// }// };// this.startCountdown()
// worker.js
export const workerCode =`
let myTimer = null;// 監聽主線程發送的消息
self.onmessage = function (event) {const { action, duration } = event.data;if (action === 'start') {// 記錄倒計時開始的時間let startTime = duration;// 使用 setInterval 每秒更新一次剩余時間myTimer = setInterval(() => {const timeLeft = startTime -1; // 剩余時間startTime=timeLeftif (timeLeft <= 0) {clearInterval(myTimer); // 清除定時器self.postMessage({ timeLeft: 0 }); // 通知主線程倒計時結束} else {self.postMessage({ timeLeft }); // 發送剩余時間給主線程}}, 1000); // 每秒更新一次} else if (action === 'stop') {// 如果收到停止消息,清除定時器clearInterval(myTimer);}
};
`