There is no doubt that JavaScript是没有多线程之说的,他只能一件事一件事的做,做完一件事再做下一件事,假如你的js要花一段比较长的时间做一件事的话,那么浏览器将会卡顿一段时间,不对用户的操作产生响应,这可咋办呢?谢天谢地,HTML5为我们提供了实现多线程的机制,这么好的东西,想必你早就再用了,不过没关系啊,咱们一块儿复习一下咯!
一、Worker类
方法介绍 (1)构造函数 new Worker(arg) :参数表示你的线程要执行的代码所在的js文件,例如‘myworker.js’,构造函数当然是返回一个Worker类的实例 (2)worker.postMessage(message):这个方法表示从主线程向子线程发送消息或者子线程向主线程发送消息,message一般是一个字符串,也可以将一个js对象转成字符串发过去 (3)worker上还有一个message事件,当有人向这个worker实例发送消息时,该事件被触发,我们可以从他的事件对象的data属性中获得post过来的值
<!DOCTYPE html> <htmllang="en"> <head> <metacharset="UTF-8"> <title>main</title> </head> <body> <divid="out"></div> <inputtype="text"name=""id="txt"> <buttonid="btn">发送</button> <scripttype="text/javascript"> var out = document.getElementById("out"); var btn = document.getElementById("btn"); var txt = document.getElementById("txt"); var worker1 = newWorker("thread1.js"); var worker2 = newWorker("thread2.js"); btn.addEventListener("click",function(){ var postData = txt.value; worker1.postMessage(postData); },false); worker1.addEventListener('message',function(e){ worker2.postMessage(e.data); },false); worker2.addEventListener('message',function(e){ out.innerText = e.data; },false); </script> </body> </html>
thread1.js
1 2 3 4 5 6 7 8 9 10
onmessage = function(event){ var res = event.data+"帅气!"; postMessage(res); } //thread2.js onmessage = function(event){ var res = event.data+"没骗你哟!"; postMessage(res); close(); }
onconnect = function(e) { var port = e.ports[0]; port.postMessage('Hello World!'); }
这是从w3c拿得一个例子,下面先看第二种方法,再做分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<!DOCTYPE HTML> <html> <head> <title>Shared workers: demo 2</title> </head> <body> <divid="log"></div> <script> var worker = newSharedWorker('shared.js'); var log = document.getElementById('log'); worker.port.addEventListener('message', function(e) { log.textContent += '\n' + e.data; }, false); worker.port.start(); // note: need this when using addEventListener worker.port.postMessage('ping'); </script> </body> </html>
shared.js
1 2 3 4 5 6 7 8
onconnect = function(e) { var port = e.ports[0]; port.postMessage('Hello World!'); port.onmessage = function(e) { port.postMessage('pong'); // not e.ports[0].postMessage! // e.target.postMessage('pong'); would work also } }