Web Worker



Creating a worker process with the Web Worker API

The Web Worker API is based on the JavaScript messaging framework. This underlying structure enables your code to send parameters to a worker and have the worker send results back.

A basic web worker is established by creating a separate file to contain the script that will be processed on the separate thread.

Web Worker offers very simple "threading" implementation:

  1. No control over the thread itself
  2. Implemented through a messaging system
    • You send messages to the worker
    • Worker sends messages to "main thread"
  3. Worker does not have the ability to update the UI

The Worker object is available from the global namespace and is created as in the following code:

<script type="text/javascript">
         var webWorker = new Worker("workercode.js");
</script>

The Worker object instantiates a new worker process and specifies what file contains the code to be run on the worker thread

The Worker object supports the functionality described in following Table.

Method Description
postMessage Starts the worker process. This method expects a single parameter containing the data to pass to the worker thread. If nothing is required in the worker thread, an empty string can be supplied.
terminate Stops the worker process from continuing.
onmessage Specifies the function for the worker thread to call back to when complete. This function accepts a single parameter in the form of EventData with a property named data containing the values.
onerror Specifies a function to call when an error occurs in the worker thread. The onerror method receives event data, including the following:
  1. message: textual message of the error
  2. filename: the filename the error occurred in
  3. line no: the line number in the file that created the error

Web worker limitations

Web workers are very convenient. They can solve many processing problems in intensive web applications. However, be aware of the limitations imposed on workers as well.

  1. Passing parameters.
    • The postMessage parameter is a string—it can take any serializable object such as native data types, JSON objects, or XML. The parameter can’t be a function.
  2. Workers don't have events for start or end:
    • Can easily be implemented through basic messaging
  3. Stopping a web worker
    • From page: worker.terminate();
    • From worker: self.close();
  4. DOM access:
    • Workers operate in their own global context, which means that they don’t have access to the DOM of the page that invoked them.

Configuring timeouts and intervals

You can set up a web worker to run on a specified interval in the background. This is done by using any existing setTimeout or setInterval methods.

  • The setTimeout method calls a specified function after the specified delay.
  • The setInterval calls the specified function repeatedly after each specified time interval.

The following code demonstrates the setTimeout and setInterval methods:

<script>
        //the following code runs the worker after 5 seconds
        var work = new Worker("workerFile.js");
        setTimeout(function(){
            work.postMessage("");
        },5000);
        //the following code runs the worker every 5 seconds:
        var work = new Worker("workerFile.js");
        setInterval(function(){
            work.postMessage("");
        },5000);
</script>

Calling Web Worker script

Web worker is established by creating a separate file to contain the script that will be processed on the separate thread.

The following code calls the web worker script:

<body>
<h2>WEB WORKER</h2>
<div>
    <label for="message">Message : </label>
    <input type="text" id="message" class="form-control" />
    <button type="button" id="send-message" class="btn">Send Message</button>
</div>
<ul id="message-list">  </ul>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
    //CREATE WORKER, AND POINT TO WORKER SCRIPT (webWorker.js)
    var worker = new Worker('./01-webWorker.js');
    setTimeout(function () {
        worker.postMessage("");
    }, 5000);
    setInterval(function () {
        worker.postMessage("");
    }, 10000);
    //RECEIVE MESSAGE FROM THE WORKER
    worker.onmessage = function (e) {
        //THE MESSAGE IS ON THE DATA PROPERTY
        var message = e.data;
        $('#message-list').append('<li>' + message + '</li>');
    }
    $('#send-message').click(function () {
        var message = $('#message').val();
        //SEND MESSAGE
        worker.postMessage(message);
    });
</script>
</body>

Web Worker script

The Web worker script executes immediately on page load, receive message from the page and sends back message to the page.

The following code demonstrates the web worker script:

<script type="text/javascript">
    //RESPONSE TO THE WORKER
    self.onmessage = function (e) {
        //THE MESSAGE IS ON THE DATA PROPERTY
        var message = e.data;
        //SEND MESSAGE TO THE PAGE
        self.postMessage(message + ' Processed Successfully');
    }
</script>

Ads Right