Javascript Web Workers

Code Snippets Web Workers
Share:

About

In this code snippet, we’ll look at web workers in Javascript.

web worker is a script that can run in the background separate from the main page javascript. This can be used to prevent blocking code. It could be considered like “multithreading” in javascript … sort of.

Let’s see the example below.

Code:

index.html
Nothing exciting here, this HTML is used just so we can add and run the code.js file for this demo.
<!DOCTYPE html>
<html>
    <head>
        <title>Web Worker</title>
    </head>
    <script src="code.js"></script>
    <body>
        <div>
            <h1>Web Worker</h1>
        </div>
    </body>
</html>
code.js
This is our main code file from where we will create the web worker.
//Check if web worker was already created ...
if (typeof(downloadWorker) == "undefined")
    downloadWorker = new Worker("downloadWorker.js"); // ... if not create it. 

//Register event to receive updates/data from worker.
downloadWorker.onmessage = function(event){
  console.log("Download progress: " + event.data + "%");

  if(event.data == 100) //If dwonload is complete ...
    downloadWorker.terminate(); //... stop and delete the web worker. 
};
dwonloadWorker.js
This file will be used to make our web worker.
let progress = 0;

//Start download.
download();

function download(){
    //Update progress.
    progress++;
    //Report progress to main file.
    postMessage(progress);
    //Simulate download.
    if(progress < 100)
        setTimeout("download()", 100); //Call this function again in 100ms.
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger