DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Web Worker: Running JS Tasks in the Background

Web Worker: Running JS Tasks in the Background

Kristof Degrave user avatar by
Kristof Degrave
·
May. 07, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
14.21K Views

Join the DZone community and get the full member experience.

Join 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.

workers

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
    postMessage(n)
}

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);
    postMessage(sortedData);
    return;
};
 
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.
Web worker

Published at DZone with permission of Kristof Degrave, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Usage of Java Streams and Lambdas in Selenium WebDriver
  • Instancio: Random Test Data Generator for Java (Part 1)
  • Toying With Kotlin’s Context Receivers
  • How BDD Works Well With EDA

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo