Chapter 8. Splitting Up Work Through Web Workers
JavaScript has, since its inception, run in a single thread. With small applications this was practical, but it runs up against certain limits now, with larger and larger applications being loaded into browsers. As more and more JavaScript is run, the application will start to block, waiting for code to finish.
JavaScript runs code from an event loop that takes events off a queue of all the events that have happened in the browser. Whenever the JavaScript runtime is idle, it takes the first event off the queue and runs the handler that goes with that event (see Figure 8-1). As long as those handlers run quickly, this makes for a responsive user experience.
Figure 8-1. Event loop
In the past few years, the competition among browsers has in part revolved around the speed of JavaScript. In Chrome and Firefox, JavaScript can now run as much as 100 times faster than it did back in the days of IE 6. Because of this, it is possible to squeeze more into the event loop.
Thankfully, most of the things JavaScript has to do are fast. They tend to be on the order of manipulating some data and passing it into the DOM or making an Ajax call. So the model in Figure 8-1 works pretty well. For things that would take longer than a fraction of a second to compute, a number of tricks can prevent bottlenecks from affecting the user experience.
The main trick ...
Get Programming HTML5 Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.