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.
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:
Moving on to the home.ts initialization:
Two properties here:
- result: Where the result of the operation will be stocked
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: