Web Workers
One of the fundamental features of client-side JavaScript is
that it is single-threaded: a browser will never run two event
handlers at the same time, and it will never trigger a timer while an
event handler is running, for example. Concurrent updates to
application state or to the document are simply not possible, and
client-side programmers do not need to think about, or even
understand, concurrent programming. A corollary is that client-side
JavaScript functions must not run too long: otherwise they will tie up
the event loop and the web browser will become unresponsive to user
input. This is the reason that Ajax APIs are always asynchronous and
the reason that client-side JavaScript cannot have a simple,
synchronous load()
or require()
function for loading JavaScript
libraries.
The Web Workers specification[54] very carefully relaxes the single-threaded requirement for client-side JavaScript. The “workers” it defines are effectively parallel threads of execution. Web workers live in a self-contained execution environment, however, with no access to the Window or Document object and can communicate with the main thread only through asynchronous message passing. This means that concurrent modifications of the DOM are still not possible, but it also means that there is now a way to use synchronous APIs and write long-running functions that do not stall the event loop and hang the browser. Creating a new worker is not a heavyweight operation like opening a new browser ...
Get JavaScript: The Definitive Guide, 6th 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.