我试图创建Web Workers并在周期中向他们发布消息:
array.forEach(function (data) { this.createWorker(); this.workers[this.workersPointer].postMessage({task: 'soMetask',data: string}); },this);
createWorker函数:
createWorker: function () { this.workersPointer++; var worker = this.workers[this.workersPointer] = new Worker('Worker.js'),storage = this; worker.onmessage = function (event) { if (event.data.error) { storage[event.data.task + 'Errback'](event.data.error); } else { storage[event.data.task + 'Callback'](event.data.data); } }; worker.onerror = function (error) { storage.workerErrback(error); }; }
工人代码:
self.addEventListener('message',function (event) { self.postMessage({ data: data,error: err,task: event.data.task });
},false);
它在Google Chrome中完美运行.当我尝试在Firefox中运行它时,它只能运行20次. Firefox网络工作者有限制吗?我在mozilla.org上找不到有关它的信息.如果没有限制,问题是什么?有任何想法吗?
解决方法
刚做了一些我自己的测试.为此,我改变了一点代码:
周期:
for(var i=0;i<200;i++){ this.createWorker(); this.workers[this.workersPointer].postMessage({task: 'soMetask',number:i}); };
createWorker函数:
this.workers =[]; this.workersPointer = 0; storage=[]; var createWorker= function () { workersPointer++; var myPointer = workersPointer; var worker = this.workers[this.workersPointer] = new Worker('Worker.js'); worker.onmessage = function (event) { if (event.data.error) { alert(event.data.error); } else { document.cookie=event.data.task+"["+myPointer+"]="+event.data.number; } }; worker.onerror = function (event) { alert("Error: " + event.error); }; }
工人:
onmessage = function(event) { postMessage({number:event.data.number*2,task: event.data.task}); };
在我运行之后,在chrome中我有66个cookie(包括一个漂亮的蓝色崩溃窗口),在firefox中我得到了20个.所以这两个浏览器似乎都有工作者限制.
编辑:
在Opera中我得到一个控制台消息:
此窗口超出了最大Web Worker实例数(16).