Over a million developers have joined DZone.

Web Worker: Running JS Tasks in the Background

DZone's Guide to

Web Worker: Running JS Tasks in the Background

· Web Dev Zone ·
Free Resource

A true open source, API-first CMS — giving you the power to think outside the webpage. Try it for free.

Since JavaScript is more and more used for building applications, rather than providing extra features, you need to take care you don’t freeze the UI. This is one of the reasons why the W3C introduced the web worker API. This API provides a way to run JavaScript in a thread different from the UI thread. This way long running code such as sorting large array’s, won’t freeze the the UI or make your application unresponsive. Generally, workers are expected to be long-lived, have a high startup performance cost and a high per-instance memory cost.


When we want to run code in a thread different from the UI thread, then we need to put this code in separate file. This file, will then be called by the worker to run in another thread. The only thing you need to do in the in the code that will run in another thread is calling postMessage method whenever you want to send data to the UI-thread.

Continuous worker

This code will start running when ever a worker with that file is instantiated and will continue running.

Example of a file (prime.js) to run in the background:

var n = 1;
prime: while(true){
    n += 1;
    for (var i = 2; i <= Math.sqrt(n); i += 1){
        if (n % i == 0){
            continue prime;
    // Found prime

This code will send a message to the UI thread every time a prime is found.

// Starts a new worker
var worker = new Worker('prime.js');
worker.onmessage = function (event){
    // event.data contains a prime
    document.getElementById("result").textContent = event.data

The code above is used to create a new worker. The worker will execute the code in the prime.js file in a thread separate from the UI. In our case, the code will start calculating which numbers are primes.

The onmessage event on the worker gets triggered every time the postMessage method is called inside the worker thread. This way we can display the prime on the screen.

Dedicated worker

This worker will only start executing when you call the postMessage method on the worker.

Example of a file (sort.js) to run in the background:

onmessage = function (event) {
    var data = event.data.data;
    var propertyName = event.data.propertyName;
    var sortedData = data.sort(JSONComparer(propertyName).sort);
function JSONComparer(propertyName) {
    return {
        sort: function (valueX, valueY) {
                return ((valueX[propertyName] == valueY[propertyName]) 
                        ? 0 : ((valueX[propertyName] > valueY[propertyName]) ? 1 : -1));

The onmessage method will handle a postMessage send to the worker. This will start the work you want to execute. In this case the code will sort an array of JSON objects on a given property. When the array and the propertyName is provided as data in the postMessage method, The data will get sorted on the property with the given propertyName. When the sort is completed, the sorted array will be send to the UI.

var worker = new Worker("sort.js");
var data = [{ name: "test2" }, [{ name: "test4" }, [{ name: "test1" }, [{ name: "test3" }]
worker.onmessage = function (event) { /* event.data contains the sorted Array */) };
worker.postMessage({ data: data, propertyName: "name"});

With the postMessage method we can provide the data that is needed to sort an array. When the sorting is completed and the postMessage method in the background thread is called, the onmessage function will be triggered in the UI thread so we can process the sorted array.

More information about workers can be found here.

The New Standard for a Hybrid CMS: GraphQL Support, Scripting as a Service, SPA Support. Watch on-demand now.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}