js worker
index.html
<!DOCTYPE html> <html> <head> <title>JavaScript Worker Example</title> </head> <body> <script> // 主线程 const mainWorker = new Worker('worker.js'); debugger; // 向 worker 发送消息 mainWorker.postMessage('Hello from main thread!'); // 接收 worker 返回的消息 mainWorker.onmessage = function(event) { console.log('Received message from worker:', event.data); }; // 监听 worker 错误 mainWorker.onerror = function(error) { console.error('Error from worker:', error.message); }; </script> </body> </html>
// worker.js // Worker 线程处理逻辑 // 接收消息并处理 self.onmessage = function(event) { debugger; console.log('Received message from main thread:', event.data); // 模拟一些计算任务 const startTime = Date.now(); while ((Date.now() - startTime) < 2000); // 休眠一段时间模拟计算任务 // 返回消息给主线程 self.postMessage('Hello from worker!'); };
http-server
用这个启动服务