Book Image

JavaScript Concurrency

By : Adam Boduch
Book Image

JavaScript Concurrency

By: Adam Boduch

Overview of this book

Concurrent programming may sound abstract and complex, but it helps to deliver a better user experience. With single threaded JavaScript, applications lack dynamism. This means that when JavaScript code is running, nothing else can happen. The DOM can’t update, which means the UI freezes. In a world where users expect speed and responsiveness – in all senses of the word – this is something no developer can afford. Fortunately, JavaScript has evolved to adopt concurrent capabilities – one of the reasons why it is still at the forefront of modern web development. This book helps you dive into concurrent JavaScript, and demonstrates how to apply its core principles and key techniques and tools to a range of complex development challenges. Built around the three core principles of concurrency – parallelism, synchronization, and conservation – you’ll learn everything you need to unlock a more efficient and dynamic JavaScript, to lay the foundations of even better user experiences. Throughout the book you’ll learn how to put these principles into action by using a range of development approaches. Covering everything from JavaScript promises, web workers, generators and functional programming techniques, everything you learn will have a real impact on the performance of your applications. You’ll also learn how to move between client and server, for a more frictionless and fully realized approach to development. With further guidance on concurrent programming with Node.js, JavaScript Concurrency is committed to making you a better web developer. The best developers know that great design is about more than the UI – with concurrency, you can be confident every your project will be expertly designed to guarantee its dynamism and power.
Table of Contents (17 chapters)
JavaScript Concurrency
About the Author
About the Reviewer

Communicating with workers

The preceding example created a web worker, which indeed ran in its own thread. But, this is not very helpful to us because we need to be able to communicate with the workers that we create. In this section, we'll cover the basic mechanisms involved with sending and receiving messages from web workers, including how these messages are serialized.

Posting messages

When we want to pass data into a web worker, we use the postMessage() method. As the name suggests, this method posts the given message to the worker. If there are any message event handlers set up within the worker, they'll respond to this call. Let's look at a basic example that sends a string to a worker:

// Launches the worker thread.
var worker = new Worker('worker.js');

// Posts a message to the worker, triggering
// any "message" event handlers.
worker.postMessage('hello world');

Now let's look at the worker that responds to this message by setting up an event handler for the message event:

// Setup...