Is Javascript Multithreaded? How it handles asynchronous actions?

By | December 14, 2018

Javascript is a single threaded application. That means you cannot run more than one script at one time to modify DOM or something.

But there are something called “Worker Threads” that spans separate threads outside your application that can do complex tasks which is linked by a Callback method.

What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

You can read more about Worker Thread from here.

Example

<script>
var w;

function startWorker() {
  if (typeof(Worker) !== "undefined") {
    if (typeof(w) == "undefined") {
      w = new Worker("demo_workers.js");
    }
    w.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else {
    document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
  }
}

function stopWorker() { 
  w.terminate(); //terminate a webworker
  w = undefined; 
}
</script>

Another Example

    var myWorker = new Worker('my_task.js');

    myWorker.onmessage = function(oEvent) {
    console.log('Worker said : ' + oEvent.data);
    };

    myWorker.postMessage('ali');

And the my_task.js will look like this

postMessage("I\'m working before postMessage(\'ali\').");

onmessage = function(oEvent) {
  postMessage('Hi ' + oEvent.data);
};

Your ‘demo_workers.js’ may be doing some heavy work, but that will be handled by the WorkerThread.

Reuse the Web Worker

If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

This is the same mechanism that is used in Single Page applications like React-Native Vue.js etc…

Post Message to the worker

To post your own message to the worker, you can use worker.postMessage([JavaScript-Object])

It will be received inside worker.onmessage() like this.

worker.onmessage(function(e)){
  if(e.yourMessage){
  }
}

The Webworker has no access to the DOM.
But it has access to so many other things such asp

1. Geolocation
2. user agent
3. Cookie enabled
4. host
5. pathname
6. href
7. Application Cache.
8. TimeOuts…(setTimeOut)
8. XMLHttpRequest and many more…

Note: You can create other worker threads from a Worker thread as well.
You can also import other scripts as well.

For Example

importScripts();                         /* imports nothing */
importScripts('foo.js');                 /* imports just "foo.js" */
importScripts('foo.js', 'bar.js');       /* imports two scripts */
importScripts('//example.com/hello.js'); /* You can import scripts from other origins */

Thanks for reading. Please leave your valuable comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *