Introduction to web workers
The web worker is, essentially, a piece of JS code which does not run in the same thread as your main application. And by thread, I literally mean a different thread. The web workers truly enable JS to work in a multi-threaded mode. A question that might arise here is, What are the differences between asynchronous operations and web workers?
If you think about it, they are more or less the same thing. The web workers take away loads from the main thread for a while and then come back with the results. However understand the fact that async
functions run on the UI thread, whereas web workers do not. Also, web workers are long-lived, and live inside a separate thread, whereas asynchronous operators, as we discussed in Chapter 4, Asynchronous Programming, follow the Event loop.
Performance-wise, web workers are also much faster than traditional asynchronous operations. Here's a test which sorts randomly generated arrays of lengths 10K and 1M as an asynchronous operation...