DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. JavaScript
  4. Web Workers, for a responsive JavaScript application

Web Workers, for a responsive JavaScript application

Giorgio Sironi user avatar by
Giorgio Sironi
·
Mar. 24, 11 · Interview
Like (1)
Save
Tweet
Share
9.56K Views

Join the DZone community and get the full member experience.

Join For Free

There is a big problem with JavaScript browser interpreters: while Ajax is by nature an asynchronous technology, all the other computations performed in JavaScript are not.

This is not necessarily an issue: after all, imperative languages like Java and PHP work like this; when you call a function the next line will be executed only after that function has returned. When you perform an XMLHttpRequest instead, you specify a callback and the moment the request starts XMLHttpRequest returns. In this scenarios, you specify a callback function which will be called after the server has responded.

Thus all JavaScript method calls, apart from Ajax-related ones, are by default synchronous. But when the browser is busy executing JavaScript, not only the subsequent lines of code are blocked: the user interface also freezes. The browser tab is blocked to avoid concurrency problems, and the user can't click nor scroll nor do anything else. If the blocks lasts for more than a few seconds, usually browsers assume JavaScript code has entered an infinite loop, and present the user with a choice:

This is an usability nightmare. We use JavaScript to avoid the latency of contacting the server for executing some logic: but at the same time we don't want to block the browser and the user experience.

An alert() is a typical example of synchronous execution, which blocks the underlying application from further computation until the user clicks Ok. You know how much alert() are annoying.

Web Workers to the rescue

Fortunately, the HTML 5 umbrella of technologies bring us Web Workers. Web Workers are lightweight, in-browser threads that we can use to execute JavaScript code without blocking the main browser process. As you probably know, multithreading can be dangerous, and in fact Web Workers are severly limited in what data they can access.

Web Workers are implemented as .js files, which are included via asynchronous HTTP requests (which are hidden from you by the Web Workers Api). When you start a Web Worker with a message, you get a separate thread of execution. I'm not aware of the various browsers implementation and if they use actually different processes, but it does not even matter here; the effect is that you are presented with multiple JavaScript threads.

Web Workers cannot manipulate the DOM nor the window or document objects; everything they need is passed to them as a scalar; this simplifies the browser's implementation and ensure a rapid adoption of the standard.

Message passing is the mean of communication between the main thread and the workers. Inside a Worker, you can perform Ajax requests with the XMLHttpRequest class, or even spawn other workers.

Example

Enough talking today. Now I'll show you some code.

This is a demonstration of a simple numerical computation: calculating if a number is prime. First, it is performed asynchronously; then a second time in the browser's main thread.

I have included a text box in which you can scroll to show how the user interface freezes. While the Web Worker is running, you're free to scroll and read the content of the box; while the browser thread is busy instead, the scrolling is blocked as well as any other action on the page. You can see this is exactly the same effect as of the alert() calls.

This code is tested in Chromium and Firefox 4. The latter will tell you that the script has become unresponsive in the scenario when you're not using a Web Worker.

Note that to instance a Web Worker, the file must be retrieved by the browser from an HTTP server. If you are under a Unix-like machine, to quickly setup a small HTTP server whose root is the current folder, enter:

python -m SimpleHTTPServer

This is the main Html page:

<script type="text/javascript">
// we will use this function in-line in this page
function isPrime(number)
{
    if (number === 0 || number === 1) {
        return true;
    }
    var i;
    for (i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) {
            return false;
        }
    }
    return true;
}

// a large number, so that the computation time is sensible
var number = "1000001111111111";
// including the worker's code
var w = new Worker('webworkers.js');
// the callback for the worker to call
w.onmessage = function(e) {
    if (e.data) {
        alert(number + ' is prime. Now I\'ll try calculating without a web worker.');
        var result = isPrime(number);
        if (result) {
            alert('I am sure, it is prime. ');
        }
    } else {
        alert(number + ' is not prime.');
    }
};
// sending a message to the worker in order to start it
w.postMessage(number);

</script>
<p style="height: 200px; width: 400px; overflow: scroll;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce blandit tristique risus, a rhoncus nisl posuere sed. Praesent vel risus turpis, et fermentum lectus. Ut lacinia nunc dui. Sed a velit orci. Maecenas quis diam neque. Vestibulum id arcu purus, quis cursus arcu. Etiam luctus, risus eu scelerisque scelerisque, sapien felis tincidunt ante, vel pellentesque eros nunc at magna. Nam tincidunt mattis velit ut condimentum. Vivamus ipsum ipsum, venenatis vitae placerat eu, convallis quis metus. Quisque tortor sapien, dapibus non vehicula quis, dapibus at purus. Nunc posuere, ligula sed facilisis sagittis, justo massa placerat nulla, nec pellentesque libero erat ut ligula. Aenean molestie, urna quis molestie auctor, lorem purus hendrerit nisi, vitae tincidunt metus massa et dolor. Sed leo velit, iaculis tristique elementum tincidunt, ornare et tellus. Quisque lacinia felis at est faucibus in facilisis dui consectetur. Phasellus sed ante id tortor pretium ornare. Aliquam ante justo, aliquam ut mollis semper, mattis sit amet urna. Pellentesque placerat, diam nec consectetur blandit, libero metus placerat massa, quis mattis metus metus nec lorem.
</p>

And this is the Web Worker implementation, webworkers.js:

function isPrime(number)
{
    if (number === 0 || number === 1) {
        return true;
    }
    var i;
    for (i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) {
            return false;
        }
    }
    return true;
}

// this is the point of entry for the workers
onmessage = function(e) {
    // you can support different messages by checking the e.data value
    number = e.data;
    result = isPrime(number);
    // calling back the main thread
    postMessage(result);
};
JavaScript application Web worker

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • [DZone Survey] Share Your Expertise and Take our 2023 Web, Mobile, and Low-Code Apps Survey
  • 5 Steps for Getting Started in Deep Learning
  • Stop Using Spring Profiles Per Environment
  • mTLS Everywere

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: