This sample demonstrates how using WebWorkers can improve the performance of highly intensive processing by executing logic on thread(s) separate from the main event thread.
Calculate # of prime numbers between 2 and (5 times):
Web Workers are designed to process logic asyncronous. As shown in the above example, performing large volumes of processing using the main event thread "freezes" the page and prevents the user from interacting. However
You cannot modify the UI from within a worker pool, because only the main event thread has access to the DOM.
Worker threads and the main thread communicate to each other by using a method named "postMessage" to send each other data, and by defining a callback method that is invoked when each receive data during their 'onmessage' event.
Since workers process data asyncronously, there is no way to predict or determine the order in which they will complete their processing.
[Main Thread] | 1. postMessage | --> | 2. onmessage(function) | [Worker Thread] |
4. onmessage(function) | <-- | 3. postMessage |
Is there a limit to how many workers can be created? I think Chrome caps it at 16. It is advised to use the .terminate() method to destroy unused Worker objects.