luo-web-worker
v1.0.3
Published
JavaScript multithreading
Downloads
2
Readme
Luo-Web-Worker
JavaScript multithreading
Install
npm install luo-web-worker -S
Usage
import WorkerWrapper from 'luo-web-worker';
let va = 1; // 对应argA参数
let vb = 2; // 对应argB参数
const worker = WorkerWrapper.run((argA, argB) => {
console.log(argA);
console.log(argB);
return 4;
}, [va, vb]).then((res) => { // res为线程函数返回值
console.log(res);
}).catch((e) => {
console.log(e);
});
long模式示例
示例一:
var worker = vm.$worker.run(() => {
self.addEventListener("message", function (e) {
console.log(e);
}, true);
// var now = Date.now();
self.postMessage('hello2');
// setTimeout(() => self.postMessage('hello2'));
// while (true) {
// if (Date.now() - now >= 5000) {
// self.postMessage('hello2');
// now = Date.now();
// }
// }
console.log(1111);
setInterval(function () {
console.log('test');
}, 2000);
return 6;
}, [], {mode: 'long', onmessage: (msg) => {
console.log(window);
console.log(msg);
}}).then(([res, worker]) => {
console.log(res);
setTimeout(() => alert(1) + worker.close(), 10000);
// setTimeout(() => alert(2) + worker.postMessage({mode: 'long', message: 'hello4'}), 10000);
}).catch((e) => {
// console.log(22);
// worker = null;
});
示例二:
const actions = [{
message: 'func1',
func: (va) => {
self.addEventListener("message", function (e) {
console.log(e);
}, true);
// var now = Date.now();
self.postMessage('hello2');
// setTimeout(() => self.postMessage('hello2'));
// while (true) {
// if (Date.now() - now >= 5000) {
// self.postMessage('hello2');
// now = Date.now();
// }
// }
console.log(1111);
setInterval(function () {
console.log('test');
}, 2000);
return 6;
}
}];
const worker = vm.$worker.create(actions);
worker.postMessage('func1', ['hhhhh'], {mode: 'long', onmessage: (msg) => {
console.log(window);
console.log(msg);
}})
.then(([res, worker]) => {
console.log(res);
// setTimeout(() => alert(1) + worker.close(), 10000);
setTimeout(() => alert(2) + worker.postMessage({mode: 'long', message: 'hello4'}), 10000);
}).catch(e => {
// console.error(e);
})
注意:
一:long模式时 " then(([res, worker]) " then里返回参数是数组,res为返回的消息,worker为worker实例对象
二:long模式时 需要用 worker.close() 手动关闭线程(需要时)
三:long模式时 主线程往worker线程发消息时一定要用 worker.postMessage({mode: 'long', message: 'xxxx'}) 这种格式
四:long模式时 worker线程里如果添加接收消息事件必需用addEventListener方式
Props
| 参数类型 | 说明 | | ---------- | ----------- | | 参数一 | 启动方法(create方式时为对应的func方法,里面如果添加接收消息事件必需用addEventListener方式) | | 参数二 | 主线程传给worker线程的参数 | | 参数三 | 配置 (可选) | | 参数三mode | 模式(默认为单向模式,如设为long则为双向可发消息,且可返回worker对象,需手动关闭线程) | | 参数三onmessage | 配置worker线程向主线程发消息事件 |
License
This content is released under the MIT License.