JS是单线程的运行模式,一件事做完开始下一件,当其中一件事卡住时,会影响后续运转。JS提供异步的方法来解决这一问题,此外还可以开多个进程,把需要大量计算或加载的事件放另一个进程,不影响主进程的进展,这就是Worker。
Worker分主进程和子进程,当前默认为主进程,创建一个子进程代码为:
//fu.js
//创建子进程
var worker = new Worker('child.js');
如果需要往子进程传参可以这样做:
//fu.js
//子进程传参
worker.postMessage({'text':'hello,child'});
子节点接收传参:
// child.js
onmessage = function (e) {
console.log(e.data.text) //hello,child
}
模拟5秒后子进程计算完,数据返给主进程:
// child.js
onmessage = function (e) {
console.log(e) //hello,child
setTimeout(()=>{
// 返回计算结果
postMessage({'text':'hello,fu'});
},5000)
}
主进程接收:
//fu.js
//获取子进程计算结果
worker.onmessage = (e)=>{
console.log(e.data.text); //hello,fu
}
完整代码如下:
//fu.js
//创建子进程
var worker = new Worker('child.js');
//子进程传参
worker.postMessage({'text':'hello,child'});
//获取子进程计算结果
worker.onmessage = (e)=>{
console.log(e.data.text); //hello,fu
}
// child.js
onmessage = function (e) {
console.log(e.data.text) //hello,child
setTimeout(()=>{
// 返回计算结果
postMessage({'text':'hello,fu'});
},5000)
}
开启多个线程会消耗系统资源,使用完最好关闭。
// fu.js
worker.terminate();
//child.js
close();
PS:在子进程使用第三方脚本可以用importScripts()方法。
//child.js
//引入脚本
importScripts("脚本名");
本篇就简单记录下Worker使用方式,其他还有些注意事项和相关API可以看阮一峰老师的博客: