Skip to content
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Delegating Consuming Task into WebWorker

Posted on: 2017-03-23

Heavy operation can hang the main thread in JavaScript. This is mainly because there is only a single thread and every operation needs to not be too much intensive. A way to handle an heavy operation is to delegate this one into a WebWorker.

A WebWorker is a place in the browser that can be requested by a page to do some task without being executed into the main thread. It has some limitations, like not being able to manipulate the Dom and being more slow, but has the main advantage to not interfere the main thread. All is done by messages between the script from the page and the script that run the worker.

To illustrate the benefit, we will use an intensive script that will be run in the main thread from one button and having a second button that execute the same script into the WebWorker. The main thread will have the time updating every 50ms as well as adding a dot. The first button will have the consequence of having the time and the dot to stop for few seconds, while the WebWorker will have always a smooth time and dot update. Here is the result of the code being executed in the main thread.