31 January 2012

Free Up The Event Loop With Web Workers

JavaScript gives us an event loop so we can set timeouts and listeners without blocking all script execution. The problem with this approach shows when you start writing CPU intensive code. The event loop can only execute one task at a time, so if one of those operations takes 5 seconds, nothing else can run until it has finished. On top of the JavaScript engine being locked during this time, the browser will not render any UI changes. This results in the entire browser freezing. As we move to heavier client side applications, this limitation becomes more obvious.

Web Workers are one of the new features in the HTML5 spec and allow us to essentially create multiple event loops. By running expensive operations in their own threads, the user experience stays responsive. Below is an example of an expensive operation implemented with and without a worker.


 

A worker is initiated by passing a JavaScript file which includes a specific event listener. No global variables from the parent are available in the worker, which includes the document and window objects. The only way to pass data in is to fire a message event to the worker with a string attached. More recently, browsers have been starting to support sending an object which will be json stringified automatically. To be safe, you should always stringify the object yourself before sending to prevent any cross browser issues.

Take a look at the source code of this page for a simple working example. You can read more about web workers here. If you have any questions, feel free to ask me.