Web Workers on Javascript for Intensive CPU Tasks

Reading Time: 4 minutes

In this article we will see how to use Web Workers to perform intensive CPU tasks in the background using setTimeout() function to simulate the same. So, we will be using setTimeout() function to simulate intensive CPU tasks.

Before We Start

JavaScript is a single-threaded environment, however in some cases we need to perform time-consuming tasks in the background and update the UI without blocking the main thread. In recent years, web workers are being used widely for background processing. They are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.

In this article we will see how to use Web Workers to perform intensive CPU tasks in the background. For the sake of simplicity, we will not be using real intensive cpu tasks, instead we will be using setTimeout() function to simulate the same. This is because setTimeout() function is a blocking function and it will block the main thread. So we will be using setTimeout() function to simulate intensive CPU tasks.

A Little Recap on CPU Parallelism

Before getting started, let us have a quick recap on cpu parallelism. It is a technique to execute multiple tasks simultaneously. Parallelism is achieved by dividing a task into smaller subtasks and executing them simultaneously. It is also used to improve the performance of a program and it can be achieved by using multi-core processors too. Multi-core processors are processors that have more than one processor core. Each processor core can execute a task simultaneously. So if we have a multi-core processor we can execute multiple tasks simultaneously. This is called parallelism.

In the context of a web browser, parallelism is achieved by using web workers. Web workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. Web workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.

There is of course some things that you should avoid while using web workers:

  • A worker can not manipulate the DOM.
  • A worker can not access the parent page.
  • A worker has limited access to the window object.

This is because web workers are designed to be independent of the main thread. So they can not access the DOM or the parent page. They can only communicate with the main thread using message passing.

Basic usage of web workers

Let us see how to use web workers. We will be using setTimeout() function to simulate intensive CPU tasks. setTimeout() function is a blocking function and it will block the main thread.

The following code will create a web worker and execute the code inside the web worker. The code inside the web worker will be executed in a separate thread. The code inside the web worker will be executed in a separate thread. This code requires a web server to run; we will use a little trick in the next section to overcome this problem.

var worker = new Worker("worker.js");

worker.postMessage("Hello World");
worker.onmessage = function(event) {
    console.log("Message received from worker");
};

Now a code tha could be executed without a server

In order to prevent the requirement of having a server to load the code of the worker, we will be using blob urls to load the worker js file. The following code will create a web worker and execute the code inside of it. The code will be executed in a separate thread.

var blob = new Blob(["onmessage = function(e) { postMessage('Hi ' + e.data); }"], {type: "text/javascript"});
var worker = new Worker(window.URL.createObjectURL(blob));

worker.onmessage = function(event) {
    console.log("Message received from worker");
};
worker.postMessage("World");

Testing the time of several tasks without using web workers

We will be using setTimeout() function to simulate intensive CPU tasks. setTimeout() function is a blocking function and it will block the main thread. So we will be using setTimeout() function to simulate intensive CPU tasks.

var start = new Date().getTime();
var tasks = 4;
var completedTasks = 0;
var task = 0;
var executeTask = function(task) {
  setTimeout(function() {
    console.log('task completed', task);
    completedTasks++;
    if (completedTasks == tasks) {
      var end = new Date().getTime();
      var time = end - start;
      console.log("Execution time no workers: " + time);
    } else {
      task++
      executeTask(task)
    }
  }, 1000);
};

executeTask(task);

Testing the time of several tasks using web workers

Let us see how to test the time of several tasks using web workers. Again, we will be using setTimeout() function to simulate intensive CPU tasks. For this example we will be using Blob URLs to load the worker js file. This will allow us to run the code without a server. If you want to know more about Blob URLs you can go here.

var blob = new Blob(["onmessage = function(e) { setTimeout(function(){ postMessage('Hi ' + e.data); }, 1000); }"], {
  type: "text/javascript"
});
var worker = new Worker(window.URL.createObjectURL(blob));
var worker2 = new Worker(window.URL.createObjectURL(blob));
var worker3 = new Worker(window.URL.createObjectURL(blob));
var worker4 = new Worker(window.URL.createObjectURL(blob));

var workers = [worker, worker2, worker3, worker4];

var start = new Date().getTime();
var tasks = 4;
var completedTasks = 0;
var executeTask = function(task, worker) {
  worker.onmessage = function(event) {
    console.log('task completed', event.data);
    completedTasks++;
    if (completedTasks == tasks) {
      var end = new Date().getTime();
      var time = end - start;
      console.log("Execution time: " + time);
    }
  };
  worker.postMessage("task " + i);
};

for (var i = 0; i < tasks; i++) {
  let worker = workers[i % workers.length];
  executeTask(i, worker);
}

We only used 4 tasks to prevent the need to introduce the use of queues. Also in this particular setup we are using setTimeout() function, so overloading the worker would be a fake test. But if you are using a real intensive CPU task you will need to use queues to prevent the use of more workers than the number of workers you have.

Conclusion

In this article we saw how to use Web Workers to perform intensive CPU tasks in the background. We also learnt how to use them to perform intensive CPU tasks in the background. There are other ways to use them, but this is the most basic way. It is also worth mentioning that there are other workers available, such as Service Workers, Shared Workers, etc. We could talk about those and its applications in another article!

Happy threading!

0 Shares:
You May Also Like