You are viewing our old blog site. For latest posts, please visit us at the new space. Follow our publication there to stay updated with tech articles, tutorials, events & more.

WEB WORKER – MULTI THREADING WITH JAVASCRIPT

0.00 avg. rating (0% score) - 0 votes

A few iterations back, we got a task to develop a page with few graphs and data listing, but processing data received from server to the data format required by charting library for 5 charts was taking time as it was a heavy computation.
You all know, JavaScript is single threaded in nature, so any heavy computation or long running JavaScript code blocks UI thread and freeze the window.
You must have seen sometime browsers shows a warning pop up like below:-

stop

This is the protection mechanism browsers implement when a long running JavaScript occurs and blocks the UI thread. But by this, we cannot make a decision as a script is not written correctly or it just needs more time.

Ex: Long – running-script

code4

To overcome this, we generally run JavaScript code in background and for that we use setTimeout() and setInterval() methods. But they still run in a single thread.

Example –

code5

Running the above code in browser, you will notice that nothing happens until you dismiss the alert box.

But now, HTML5 gives us an API to help us for running my heavy computational/long-scripts in background independently of other user interface scripts.

WEB WORKERS

We used separate JavaScript processes running in separate threads in CSM for Dashboard page which consists of graphical representation of various data metrics. We used workers to do the calculation and convert our JSON input to the object required by charting libraries and rendered all graphs at same time without blocking the UI thread.

These separate JavaScript process running in separate thread are Web Workers

Web workers have certain features.

  • They execute concurrently
  • They don’t block the UI
  • They allow you to extract up to the last drop of juice from a multicore CPU.
  • Workers can be dedicated (single tab) or shared among tabs/windows.
  • To create Worker, we put JavaScript in separate file and create new Worker instance:
    • var worker = new Worker(‘extra_work.js’);
  • We communicate with worker using postMessage function and onmessage

Steps to write code to be run by web worker

  1. Add event listener to the worker itself
 

 

this.addEventListener(‘message’, function(event){
// your code to run on worker’s start
}, false);

2. To communicate with code send message to worker(self) object

this.postMessage(“<result to be returned after processing>”);

Steps to use Web Workers

  1. Instantiate Worker for javascript you want to run.
var newWorker = new Worker(“../myWorker.js”);
  1. Start web worker by posting a message by providing inputs as string or json
newWorker.postMessage(“input for worker”);
  1. Listen from worker
newWorker.addEventListener(“message”, function(event) {
var data = event.data;
// do processing on data
}, false);

Sample code

helloWorker.js

code2

index.html

code6

As you run the above code in browser, you will notice that worker code is executes in parallel, and after processing you will receive the data back.

Limitations of Web Workers

  • No Access:
    • DOM
    • Window
    • Document
    • Parent
    • Main App Memory/Object
  • You Do Have Access To
    • XHR
    • Navigator , Location
    • App cache
    • Import script
  • No support for IE Browser < = 9.0

Useful For:-

  • Background number crunching
  • Background notification from server to local database
  • Background updating from server
  • Search queries
  • Prefetching data for later use
  • Process large arrays or JSON responses

One thought on “WEB WORKER – MULTI THREADING WITH JAVASCRIPT

Comments are closed.