查看详情请跳转:一文彻底学会使用web worker - 掘金 (juejin.cn)/web worker - 枫叶布 - 博客园 (cnblogs.com),本文仅作笔记记录
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试</title> </head> <body> <p id="show-txt"></p> <button onclick="sendBtn()">发送数据</button> <button onclick="closeBtn()">关闭</button> <script type="text/javascript"> /** Worker参数: path 有效的js脚本的地址,必须遵守同源策略。无效的js地址或者违反同源策略,会抛出SECURITY_ERR类型错误 options.type 可选,用以指定worker 类型。该值可以是classic或module。 如未指定,将使用默认值classic options.credentials 可选,用以指定 worker 凭证。该值可以是omit,same-origin,或include。如果未指定,或者 type 是classic,将使用默认值omit(不要求凭证) options.name 可选,在DedicatedWorkerGlobalScope的情况下,用来表示worker 的 scope 的一个DOMString值,主要用于调试目的。 // 代码: const tempWorker=new Worker(path,options); // 接收消息 tempWorker.onmessage=function(e){ console.log(e.data); }; // 发送消息 tempWorker.postMessage("消息内容"); // 监听错误消息 tempWorker.onerror = function(e){ console.log(e.data); } // 当 message 事件接收到无法被反序列化的参数时触发 tempWorker.onmessageerror = function(e){ console.log(e.data); } // 关闭Worker tempWorker.terminate(); */ var tempWorker=null; try{ // 使用默认的options //tempWorker=new Worker("worker.js"); var tempOptions={ name:"测试添加worker名称" }; tempWorker=new Worker("worker.js",tempOptions); // 监听错误消息 tempWorker.onerror = function(e){ console.log(e.data); } // 当 message 事件接收到无法被反序列化的参数时触发 tempWorker.onmessageerror = function(e){ console.log(e.data); } // 接收消息 tempWorker.onmessage=function(e){ //console.log(e.data); document.getElementById('show-txt').innerHTML = "接收信息:"+e.data; }; }catch(e){ console.log(e); alert("创建Worker错误!!!"); } function sendBtn(){ try{ tempWorker.postMessage(2); }catch(e){ console.log(e); alert("发送错误!!!"); } } function closeBtn(){ try{ tempWorker.terminate(); }catch(e){ console.log(e); alert("关闭出错!!!"); } } </script> </body> </html>
worker.js
// 引入其他脚本 // self.importScripts("worker.js"); // 进行步进显示 function runWorkerDemo(stepNum){ var _self=self; var i=0; // 注:window.setInterval是不可用的 var tempInterval= setInterval(function(){ // 发送数据 _self.postMessage(stepNum*i); if(i>=100){ // 关闭 Worker 线程。 _self.close(); } else if(i>=10000){ // 定时清除,注:这一步无法达到,因为当i=101是,线程便被"_self.close()"关闭 clearInterval(tempInterval); } i++; },100); }; console.log("打印Worker名称:"+self.name); // 自启动 // runWorkerDemo(2); // 监听启动 self.onmessage=function(e){ console.log("打印监听启动:"+e.data); runWorkerDemo(e.data); };
// 待续。。。