Using the worker, developers can now run code containing extensive computations within the background, without fear about the UI layer being blocked. Let’s have a better check out how the workers make this possible.
The HTML5 markup shows the only use of a worker for performing a computationally expensive task without interrupting the interface. during this example, the most document creates a worker to compute prime numbers, and display the foremost recently found prime. The output of this document’s body may be a single line of text which says “The highest prime discovered thus far is: ________ “. The dashed area is in fact replaced by the results of the worker.
It might not be a smart idea to use a worker just to show a small line of text (on a webpage); but if you have been following closely, you may have found that the script written to measure the prime numbers would run itself until infinity. Until the kingdom arrives, or the browser window is closed, it will keep updating the result section with the newest prime number found. If the same logic had been used without a worker to produce the same result, the browser window would have crashed in less than 30 seconds.
Restrictions and limitations
When to use them
A worker is best fitted to situations where we’ve to affect third-party APIs that force the most thread to attend for a result, before proceeding to a subsequent statement. In such cases, we will delegate this task to a newly spawned worker to leverage its asynchronous capability to our benefit.
Tuts+, a blog that offers tutorials and technical articles, talks about how there might come a time once we got to process an enormous amount of knowledge returned by the server, as seen within the above example. Traditionally, processing such data negatively impacts the application’s responsiveness, thereby making the UX unacceptable. A more elegant solution would be to divide the processing work among several workers to process non-overlapping portions of the info, thus taking multi-threading to a subsequent level. Web workers also help in polling, where we continuously poll a destination within the background and post messages to the most thread when new data is received, making them a very smart choice.