How to Use Web Workers With Ionic in One Go

Web Workers are very useful for handling heavy calculations. The code is working in a background thread and the UI can be used with no issue.
Web Workers are available in traditional JavaScript and that’s what we are going to use in our Ionic mobile application.
We will create an application that will use one of the most famous algorithm: the QuickSort algorithm.

Let’s create a new Ionic project:

And update the home.html file:

The result of the algorithm will be displayed there. If you are not familiar with this algorithm, it orders an array by swapping the numbers until it’s properly ordered, here is an example:

Ionic Web Worker Quicksort-example

Moving on to the home.ts initialization:

Two properties here:

  1. result: Where the result of the operation will be stocked
  2. ngZone: Angular tracks changes in the JavaScript files and update the properties in the templates. This is done by putting all of those methods, hooks, etc. in a zone that is watched. Web Workers aren’t in this zone so everything related to a Web Worker won’t be detected by Angular and our template won’t change. In order to include some code into this zone, the NgZone Service will be used

Let’s populate our constructor now:

A new Web Worker will be created by using the code located in assets/workers/worker.js.

The onmessage callback will be used to acquire the result of the Web Worker’s process. As stated before, Angular’s Zone doesn’t watch what is happening here, we have to notify it by using the ngZone’s run method.
The result property will be updated using the event.data property and joining the array’s content to create a string.

Once the callback is prepared, we are ready to use the postMessage method to send a message to the Web Worker.

Moving to the web-worker.js file:

When a message is received, the startQuickSort custom method is triggered. We don’t really care about the message however, the event parameter here is generally used to trigger different methods according to the message’s type.

The startQuickSort method is as follow:

A new array of random number is created. This is done by creating a new Array of 20 undefined values then using the map method to loop on each value, generate a random number and return a new array.

Once the unordered array is ready, a quickSort custom method is used to sort it.
Finally the Web Worker’s postMessage method sends the result back to the callback located in the home.ts file.

Here is the whole quickSort algorithm:

BONUS CONTENT
Enter your email address in the box below to get access to this tutorial (and others) source code.

No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *

3 Shares