JavaScript Web Workers: A Beginner's Guide


Originally published at:

In 2019, the web ecosystem has evolved to the point where the browser is an execution environment for applications built on JavaScript. This is reflected in the speed with which the industry comes up with new frameworks, paradigms, module loaders and bundlers, dependency managers, build tools, and package managers year after year.

When JavaScript was conceived in the early days of the internet, the direction of web development was not clear. Due to the constant, rapid change in the industry and ecosystem, the need for backward-compatibility with browsers and web standards, the evolution of JavaScript became a constant stream of patches, hacks and afterthoughts.

Today's mobile devices normally come with 8+ CPU cores, or 12+ GPU cores. Desktop and server CPUs have up to 16 cores, 32 threads, or more.

In this environment, having a dominant programming or scripting environment that is single-threaded is a bottleneck.

JavaScript Is Single-threaded

This means that by design, JavaScript engines — originally browsers — have one main thread of execution, and, to put it simply, process or function B cannot be executed until process or function A is finished. A web page's UI is unresponsive to any other JavaScript processing while it is occupied with executing something — this is known as DOM blocking.


Shouldn’t you be using event listeners rather than inline JS?


Hi, gandalf, yes, in a real-life project that would probably be the better approach.
The purpose here was to give a quick-and-dirty introduction to web workers.