About
In this code snippet, we’ll look at web workers in Javascript.
A 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.
}





