万象更新 Html5 - h5: h5 通过 web worker 实现多线程
示例如下:
h5\webWorker\worker.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>通过 web worker 实现多线程</title>
</head>
<body>
<!--注:运行本示例时,必须要在一个 web server 中运行,不能通过直接打开本地文件的方式运行-->
<button id="buttonStartThread">启动 worker 线程</button>
<div id="result"></div>
<script>
let buttonStartThread = document.getElementById('buttonStartThread');
buttonStartThread.onclick = function() {
let worker = new Worker('worker.js');
// UI 线程给 worker 线程传递数据
worker.postMessage(new Date());
// 收到 worker 线程发过来的数据
worker.onmessage = function(event) {
let data = event.data;
console.log("从 worker 线程收到数据", data);
}
}
</script>
</body>
</html>
h5\webWorker\worker.js
// worker 线程不能操作 DOM
let workerId = (Math.floor(Math.random() * 1000000)).toString().padStart(6, "0");
console.log("worker 线程启动了,workerId: " + workerId);
// 在 worker 中 直接写 onmessage 方法即可
// 收到 UI 线程发过来的数据
onmessage = function(event) {
let data = event.data;
console.log("从 UI 线程收到数据", data);
console.time("时长");
let now = new Date().getTime();
let cur = new Date().getTime();
do {
cur = new Date().getTime();
} while (cur - now < 1000)
console.timeEnd("时长");
// worker 给 UI 线程传递数据
postMessage(`线程 ${workerId} 返回的数据`);
};
标签:console,万象更新,worker,h5,let,线程,多线程,data From: https://www.cnblogs.com/webabcd/p/18428712/html5_h5_webWorker_worker