Chapter 5
Delegating Tasks to Web Workers
In This Chapter
• Introducing Web Workers
• Describing major API functions
• Looking at examples
• Creating a worker-based board module
IN THIS CHAPTER , I show you how to use Web Workers, a cool feature that came out of the Web Hypertext Application Technology Working Group (WHATWG; refer to Chapter 1 for more on this group). I begin by describing what workers can do, their limitations, and the functions and objects available to them.
I then move on to a few simple examples and show you how to move a CPU-intensive task to a worker to keep the browser responsive to user interaction.
Finally, I show you how to use Web Workers to create a worker-based version of the board module you implement in Chapter 4.
Working with Web Workers
JavaScript is single threaded by design. You cannot run multiple scripts in parallel; the browser processes any request you send it in a serial manner. When you use functions such as setTimeout() and setInterval(), you may think you're spawning separate threads that run independently from the main JavaScript thread, but in reality, the functions they call are pushed onto the same event loop that the main thread uses. One drawback is that you cannot have a function that blocks the execution and expect the browser to behave. For example, the XMLHttpRequest object used in Ajax has both synchronous and asynchronous modes. The asynchronous mode is used the most by far because synchronous requests tie up the thread, ...
Get HTML5 Games: Creating Fun with HTML5, CSS3 and WebGL, 2nd Edition 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.