e.g.
worker.postMessage(data1);
worker.postMessage(data2);
And inside the webwoker,assuming there's quantity of issues to be deal with,would worker.postMessage(data2)
block before completing the data1
Web workers don't make javascript multi-threaded in any way that it wasn't before, think about it like this: you're essentially starting another single-threaded process and communicating with it, like you would be able to in node. js for example.
Best Practices for JavaScript Promises JavaScript is a single-threaded language which means that a JavaScript script is only capable of executing commands, or lines of code, in a single, sequential fashion; one after another, after another.
As you may probably know, Javascript is single-threaded. To clarify better, this means that one single thread handles the event loop. For older browsers, the whole browser shared one single thread between all the tabs.
Node. js runs JavaScript code in a single thread, which means that your code can only do one task at a time. However, Node. js itself is multithreaded and provides hidden threads through the libuv library, which handles I/O operations like reading files from a disk or network requests.
A single worker executes its task in queue, i.e. one task at 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
The tasks are always finished in order, i.e. first the slow one, then the quick one. (If the task were executed in parallel, the second task would finish first with a clear margin.)
(Just to be clear: calling postMessage always blocks in its execution context (as any function call) but effectively returns "immediately", because posting the message itself is very quick operation. That's probably not what you asked.)
Note: Chrome throws a security exception if you try to load the worker.js from local disk, works in Safari & Firefox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With