一、什么是多线程
二、Concurrent.Thread.js
<meta charset="utf-8" />
<script src="Concurrent.Thread.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><style>div{width:100px;height: 100px;cursor: pointer;background: orange;}
</style><div id="test">测试点击
</div><script>Concurrent.Thread.create(function(){$('#test').click(function(){alert(1);});// 下面有一段特别复杂的函数for(var i = 0;i < 1000000;i++){console.log(i);}});</script><!--/*** 异步事件队列,负责执行alert(1)*/-->
三、WebWork
index.html
<meta charset="utf-8" />
<!--<script src="Concurrent.Thread.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><style>div{width:100px;height: 100px;cursor: pointer;background: orange;}
</style><div id="test">测试点击
</div><script>$('#test').click(function(){alert(1);});var worker = new Worker('task.js');worker.onmessage = function(event){alert(event.data);}worker.postMessage(100000);</script>
task.js
onmessage = function(event){var num = event.data;var result = 0;for(var i = 0;i< num;i++){result +=i;}// 向线程创建源送回消息postMessage(result);
}
ShareWebWorker
共享型web worker主要适用于多连接并发的问题
index.html
<meta charset="utf-8" />
<!--<script src="Concurrent.Thread.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><style>div{width:100px;height: 100px;cursor: pointer;background: orange;}
</style><div id="test">测试点击
</div><script>$('#test').click(function(){alert(1);});var worker = new SharedWorker('task.js');
worker.port.addEventListener('message',function(e){console.log(e.data);
},false)// 发送信息
worker.port.start();
worker.port.postMessage(100);</script>
task.js
var result = 0;
onconnect = function(e){var port = e.ports[0];port.postMessage('connection success!');port.onmessage = function(e){if(e.data !== 'get'){for(var i = 0;i < e.data;i++){result += i;}}port.postMessage(result);}
}
test.html
<meta charset="utf-8" />
<!--<script src="Concurrent.Thread.js"></script>-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><style>div{width:100px;height: 100px;cursor: pointer;background: orange;}
</style><div id="test">测试点击
</div><script>$('#test').click(function(){alert(1);});var worker = new SharedWorker('task.js');
worker.port.addEventListener('message',function(e){alert(e.data);
},false)// 发送信息
worker.port.start();
worker.port.postMessage('get');</script>