js中的webworker
webworker的作用类似于java的多线程
以独立文件的形式运行webworker
- index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="showBox"></div> <script> if(window.Worker) { var worker = new Worker("./test.js"); worker.postMessage(10); worker.onmessage = function(event) { document.getElementById("showBox").innerText = event.data; if(event.data == 10) { worker.terminate(); // 终止worker } } }else{ alert("你的浏览器不支持worker"); } </script> </body> </html>
- test.js
var i = 0, count = 0; self.onmessage = function(e) { count = e.data; } function countNumber() { if(i < count){ i = i + 1; self.postMessage(i); // 将信息发送到主线程上 } console.log(i); setTimeout(countNumber, 500) } countNumber();
原文地址:https://www.cnblogs.com/ye-hcj/p/10352897.html
时间: 2024-10-08 12:22:33