Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
JavaScript Concurrency
JavaScript Concurrency

JavaScript Concurrency: Build better software with concurrent JavaScript programming, and unlock a more efficient and forward thinking approach to web development

Arrow left icon
Profile Icon Adam Boduch
Arrow right icon
S$46.99 S$52.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (8 Ratings)
eBook Dec 2015 292 pages 1st Edition
eBook
S$46.99 S$52.99
Paperback
S$66.99
Subscription
Free Trial
Arrow left icon
Profile Icon Adam Boduch
Arrow right icon
S$46.99 S$52.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (8 Ratings)
eBook Dec 2015 292 pages 1st Edition
eBook
S$46.99 S$52.99
Paperback
S$66.99
Subscription
Free Trial
eBook
S$46.99 S$52.99
Paperback
S$66.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

JavaScript Concurrency

Chapter 2. The JavaScript Execution Model

The first chapter of this book explored the state of JavaScript concurrency. Generally speaking, dealing with concurrency in JavaScript applications is anything but a trivial matter. There's a lot to think about when writing concurrent JavaScript code, and the kind of solutions that we come up with are often unorthodox. There's a lot of callbacks, and wading through all of them is enough to drive a person insane. We also caught a glimpse of how our pattern of writing concurrent JavaScript code has started to change with existing concurrency components. Web workers have started to mature, and JavaScript language concurrency constructs have only just been introduced.

The language and the runtime environment only get us partway there. We need to think about concurrency at the design level, rather than after the fact. Concurrency should be the default. This is easy to say and very difficult to do. Throughout this book, we're...

Everything is a task

When we visit a web page, a whole environment is created for us within the browser. This environment has several subsystems that enable the webpage we're looking at to look and behave as it should according to World Wide Web Consortium (W3C) specs. Tasks are the fundamental abstraction inside a web browser. Anything that happens is either a task itself, or a smaller part of a larger task.

Note

If you're reading any of the W3C specifications, the term "user agent" is used instead of "web browser". In 99.9% of cases, the major browser vendors are what we're reading about.

In this section, we'll look at the major components of these environments, and how task queues and event loops facilitate the communication between these components, to realize the overall appearance and behavior of the web page.

Meet the players

Let's introduce some terminology that will help us throughout the various sections in this chapter:

  • Execution environment...

Execution contexts

Now it's time to look at the JavaScript interpreter itself—the component that takes over from other browser components when events take place and code needs to run. There's always an active JavaScript context, and within the interpreter, we'll find a stack of contexts. This is similar to many programming languages where stacks control the active context.

Think of the active context as a snapshot of what's happening right now in our JavaScript code. A stack structure is used because the active context can change to something else, such as when a function is called. When this happens, a new snapshot is pushed onto the stack, becoming the active context. When it's done running, it's popped from the stack, leaving the next context as the active context.

In this section, we'll take a look at how the JavaScript interpreter handles context switching, and the internal job queue that manages the context stack.

Maintaining execution state

The...

Creating tasks using timers

So far in this chapter, we've had a look at all the inner workers of the web browser environment, and where the JavaScript interpreter fits in this environment. What does all this have to do with applying concurrency principles to our code? With the knowledge of what's happening under the hood, we have a greater insight into what's happening when a given chunk of our code is run. Particularly, we know what's happening relative to other code chunks; time ordering is a crucial concurrency property.

This being said, let's actually write some code. In this section, we'll use timers to explicitly add tasks to the task queue. We'll also learn when and where the JavaScript interpreter jumps in and starts executing our code.

Using setTimeout()

The setTimeout() function is staple in any JavaScript code. It's used to execute code at some point in the future. New JavaScript programmers often trip over the setTimeout() function because...

Responding to DOM events

In the preceding section, we saw how to schedule JavaScript code to run at a later time. This is done explicitly by other JavaScript code. Most of the time, our code runs in response to user interactions. In this section, we'll look at the common interface that's used not only by DOM events, but also by things such as network and web worker events. We'll also look at a technique for dealing with large volumes of similar events—called debouncing.

Event targets

The EventTarget interface is used by many browser components, including DOM elements. It's how we dispatch events to elements as well as listen to events and respond by executing a callback function. It's actually a very straightforward interface that's easy to follow. This is crucial since many different types of components use this same interface for event management. We'll see as we progress through the book.

The same task queue mechanisms that execute the callback...

Responding to network events

Another critical piece of any front-end application is network interactions, fetching data, issuing commands, and so forth. Since network communications are an inherently asynchronous activity, we have to rely on events—the EventTarget interface to be precise.

We'll start by looking at the generic mechanism that hooks up our callback functions with requests and getting responses from the back-end. Then, we'll look at how trying to synchronize several network requests creates a seemingly hopeless concurrency scenario.

Making requests

To interact with the network, we create a new instance of XMLHttpRequest. We then tell it the type of request that we want to make—GET versus POST and the request endpoint. These request objects also implement the EventTarget interface so that we can listen for data arriving from the network. Here's an example of what this code looks like:

// Callback for successful network request,
// parses JSON data.
function...

Everything is a task


When we visit a web page, a whole environment is created for us within the browser. This environment has several subsystems that enable the webpage we're looking at to look and behave as it should according to World Wide Web Consortium (W3C) specs. Tasks are the fundamental abstraction inside a web browser. Anything that happens is either a task itself, or a smaller part of a larger task.

Note

If you're reading any of the W3C specifications, the term "user agent" is used instead of "web browser". In 99.9% of cases, the major browser vendors are what we're reading about.

In this section, we'll look at the major components of these environments, and how task queues and event loops facilitate the communication between these components, to realize the overall appearance and behavior of the web page.

Meet the players

Let's introduce some terminology that will help us throughout the various sections in this chapter:

  • Execution environment: This container gets created whenever...

Execution contexts


Now it's time to look at the JavaScript interpreter itself—the component that takes over from other browser components when events take place and code needs to run. There's always an active JavaScript context, and within the interpreter, we'll find a stack of contexts. This is similar to many programming languages where stacks control the active context.

Think of the active context as a snapshot of what's happening right now in our JavaScript code. A stack structure is used because the active context can change to something else, such as when a function is called. When this happens, a new snapshot is pushed onto the stack, becoming the active context. When it's done running, it's popped from the stack, leaving the next context as the active context.

In this section, we'll take a look at how the JavaScript interpreter handles context switching, and the internal job queue that manages the context stack.

Maintaining execution state

The stack of contexts within the JavaScript...

Left arrow icon Right arrow icon

Key benefits

  • *Apply the core principles of concurrency to both browser and server side development
  • *Explore the latest tools and techniques at the forefront of concurrent programming, including JavaScript promises, web workers, and generators
  • *Learn how concurrent and parallel programming can help you tackle the challenges of fast, data heavy web development

Description

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.

Who is this book for?

JavaScript Concurrency is written for any JavaScript developer who wants to learn how to write more efficient, powerful, and maintainable applications that utilize the latest developments in the JavaScript language. All aspects of concurrent, asynchronous, and parallel programming are covered from first principles and by the end of the book you’ll be able to create a fully-worked application that leverages all the topics covered in the book.

What you will learn

  • *Understand exactly how JavaScript works in a web browser environment, and how these mechanisms power our event-driven JavaScript code
  • *Use promises to turn complex synchronization scenarios into readable and maintainable values
  • *Compute values lazily and avoid unnecessary memory allocations using generators.
  • *Write concurrent code that doesn't feel like concurrent code by abstracting away boilerplate chores
  • *Leverage true hardware parallelism with web workers to get a better performance
  • *Get to grips with the NodeJS model of concurrency and learn why it's good for I/O-intensive web applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 29, 2015
Length: 292 pages
Edition : 1st
Language : English
ISBN-13 : 9781785880261
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 29, 2015
Length: 292 pages
Edition : 1st
Language : English
ISBN-13 : 9781785880261
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 178.97
Mastering JavaScript
S$66.99
JavaScript Concurrency
S$66.99
Javascript Unlocked
S$44.99
Total S$ 178.97 Stars icon

Table of Contents

11 Chapters
1. Why JavaScript Concurrency? Chevron down icon Chevron up icon
2. The JavaScript Execution Model Chevron down icon Chevron up icon
3. Synchronizing with Promises Chevron down icon Chevron up icon
4. Lazy Evaluation with Generators Chevron down icon Chevron up icon
5. Working with Workers Chevron down icon Chevron up icon
6. Practical Parallelism Chevron down icon Chevron up icon
7. Abstracting Concurrency Chevron down icon Chevron up icon
8. Evented IO with NodeJS Chevron down icon Chevron up icon
9. Advanced NodeJS Concurrency Chevron down icon Chevron up icon
10. Building a Concurrent Application Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(8 Ratings)
5 star 62.5%
4 star 12.5%
3 star 12.5%
2 star 0%
1 star 12.5%
Filter icon Filter
Top Reviews

Filter reviews by




SuJo Jan 31, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book delivers on JavaScript Concurrency no questions asked. Organized, clear, and concise examples are abound. Everything worked as expected. UI Freezing is a think of the past with the knowledge learned from this book. I really enjoyed the parallelism chapter, this is one of the key components that can cause sluggish UI, or turn something that is great into a complete loss. I had no issues following a long in this book, which is really nice after a few of the titles I've used to reference from lately.
Amazon Verified review Amazon
ruben Jan 16, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Hello this is a very important guide for developers that are interesting in develop software that can help the code that are developing in how toavoid the structures and make the code more efficient using Java.I really recommend this titile, because it has something new the content is very clear and I coul apply every that the book has.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.
Amazon Verified review Amazon
Winston Jan 22, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Javascript for quite sometime has been the most widely used programming language for web development and soon to be mobile development. In Javascript Concurrency the authors introduce readers to the principles of javascript concurrency (parallelism, synchronization, and conservation). If any of these are new to you dont worry u will learn about each and everyone with well crafted examples.Love the book!
Amazon Verified review Amazon
Sven R. Aug 08, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The chapters are concise and clear, and the content is excellent. The final chapter where you build your concurrent could be embellished further, but all in all, you can't go wrong with this book.
Amazon Verified review Amazon
Perry Nally Jan 31, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Important read for those who already understand a bit of javascript. Concurrency is an advanced topic in JS, but well worth the read. Make sure you have ample time to sit down and follow along.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon