15 Mar 2021

How to use JavaScript Worker Thread?

Hi guys, In this post I will tell you that how you can create Worker Thread under the Browser's JavaScript?

What is Worker Thread in JavaScript?

worker thread is a Thread / Block of codes that's actually runs in Background, Separate from main thread. Main thread is only used to bind communication between user's intraction and app's activity. It's not build to work with havely work and longer running task.
Worker thread is define to work with heavy intensive computing work.

Worker thread works in background, And Computed data send to UI/Main thread. Thus, cause web application don't lag, 

How to use Worker Thread?

Background/Worker Thread

Here, I created an script tag with id worker and type javascript/worker.
in script, id has been assigned for retrieve this element under DOM JavaScript.
type attribute has been assigned, so that this script should be not run.

Worker Thread Codes

It is Worker Thread implementation, Here DedicatedWorkerGlobalScope object is present as Global.

<script id="worker1" type="javascript/worker">
    var scope = this; 
   // [object DedicatedWorkerGlobalScope] var timer = (e) =>{
        postMessage(""+ Date.now() +""+ t);   
        setTimeout(timer, 100);

Main Thread

Under the this script tag, we create a Blob object.

var blob = new Blob([




        var worker = new Worker(URL.createObjectURL(blob));


        var sendTime; 

        worker.onmessage = function(e) {

      demo.innerHTML = e.data;




No comments:

No Comments