Use Javascript Web Workers for Multithreaded JS execution in the browser

Vanilla JS Advanced Topics

Alex Z
3 min readOct 3, 2022

The Web Worker API allows you to run a JavaScript program on a background thread in the browser. The advantage of this is that you can start long-running computations inside of your web worker and know that the primary thread will be available for the browser to update the UI, and run Javascript code.

credit: https://unsplash.com/@susan_wilkinson

The running Web Worker defines handlers for receiving data from the main thread as well and sending responses back to the main thread, thereby allowing communication of data to and from your main application scripts.

You can run any Javascript code inside the worker thread, but you can’t directly manipulate the DOM or access many default methods and properties of the window object. The Mozilla article on web workers also highlights the ability of web workers to access some specific browser APIs — notably Websockets and IndexedDB.

So let’ stake a simple case, and apply a Web worker to it.

First, we’ll create a web worker script, let’s call in ww.js. It will have a simple event listener, added to the special keyword ‘self’, which in the webworker script refers to the webworker itself.

Note: when used in a script that…

--

--

Alex Z

Software Developer + Product Manager. Interested in Travel, Culture, Economics and the Internet. Join Medium: https://tinycode.medium.com/membership