Is the webworker itself multithreaded?

eg.

worker.postMessage(data1); worker.postMessage(data2); 

And inside webwoker, assuming the number of problems to deal with, worker.postMessage(data2) block until data1 completes

+8
javascript html5
source share
1 answer

One worker performs his task in the queue, that is, one task in time. Try the following example:

 <!DOCTYPE html> <script> var worker = new Worker('worker.js'); worker.postMessage({ task: 1, iterations: 100 }); // very slow task worker.postMessage({ task: 2, iterations: 1 }); // very quick task worker.onmessage = function(event) { console.log(event.data); }; </script> 

worker.js:

 self.onmessage = function(event) { for (var i = 0; i < event.data.iterations * 1000 * 1000 * 10; i++) {}; self.postMessage("Finished task " + event.data.task); } 

Ouput:

 Finished task 1 Finished task 2 

Tasks always end in order, that is, first slow and then fast. (If the task was completed in parallel, the second task would first finish with a clear margin.)

(Just to be clear: a postMessage call always blocks execution in its context (like any function call), but effectively returns β€œimmediately” because posting the message itself is very fast. This is probably not what you requested.)

Note. Chrome throws a security exception if you try to download work.js from a local drive, it works in Safari and Firefox.

+5
source share

All Articles