Javascript Web Workers

Code Snippets Web Workers


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.


Nothing exciting here, this HTML is used just so we can add and run the code.js file for this demo.
<!DOCTYPE html>
        <title>Web Worker</title>
    <script src="code.js"></script>
            <h1>Web Worker</h1>
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: " + + "%");

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

//Start download.

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

Resulting output:


Leave a Reply

Your email address will not be published.

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