Using WebWorkers

Using WebWorkers

One thing commonly seen as a limitation of JavaScript is the lack of a decent parallelization paradigm. Given the humble beginnings of the language, it is no surprise that one of the more complex aspects of language design was left out. JavaScript opted for a simpler event-loop based scheduling. It has the benefit of being able to accomplish much of what a programmer would need in dealing with asynchronous problems. All the while, it is easier to implement and reason about.

The real limitation of this model comes when you want to prioritize some parts of execution over another. Anyone who has used a browser has probably run into this error before: unresponsive page

This is what happens when any bit of JS is too taxing on your processor. One line of bad code can kill the whole webpage.

WebWorkers attempt to solve this issue. Before browsers started to implement this, the only way you could run multiple scripts with different execution paths would be to open up a frame. The API for dealing with WebWorkers actually very similar to communicating between iframes.

Since it can be hard to fully convey a busy web page in snippet of code, I thought a good example would be to do a heavy math calculation. My example computes pi but allows you to pause at any point. Without WebWorkers, the command to pause the calculation would get jumbled in with the rest of the instructions on the event loop, causing indeterminate behavior. Doing it an a WebWorker allow for a much more responsive button and will stop it in a more predictable manner.

As you can see, there is much not overhead to starting a worker. You create a worker object, give it a script, and communicate across them using postMessage. A lot large web applications like Twitter, Facebook, and Gmail now use WebwWrkers precisely for that manner. When you handle all of the UI in one worker and other operations in another, you can provide a interface that feels more like a native application.