-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Web applications are becoming more complex, and JavaScript often needs to handle heavy tasks such as calculations, data processing, or API calls. Running these tasks directly on the main thread can slow down the page, making it unresponsive.
The Web Worker API solves this problem by allowing JavaScript to run scripts in the background without blocking the main thread.
A Web Worker is a separate JavaScript thread that runs alongside your main web page. It can:
Perform tasks without blocking the user interface
Communicate with the main thread using messages
Improve performance for CPU-intensive operations
Important: Web Workers cannot access the DOM directly. They work independently and communicate with the main page via messages.
Dedicated Workers
Only connected to the script that created them.
Most commonly used.
Shared Workers
Can be accessed by multiple scripts from different windows or tabs.
Useful for shared background tasks.
In this tutorial, we focus on dedicated workers.
A Web Worker is created using the Worker
constructor.
worker.js
// Worker script - runs in a separate thread
self.onmessage = function(event) {
const number = event.data; // Receive data from main thread
let result = 0;
// Perform a heavy calculation (sum from 1 to number)
for(let i = 1; i <= number; i++) {
result += i;
}
// Send result back to main thread
self.postMessage(result);
};
<input type="number" id="num" placeholder="Enter a number">
<button id="calculateBtn">Calculate Sum</button>
<p id="output"></p>
<script>
const output = document.getElementById("output");
const worker = new Worker("worker.js"); // Create a worker
document.getElementById("calculateBtn").addEventListener("click", function() {
const num = document.getElementById("num").value;
// Send data to worker
worker.postMessage(Number(num));
output.textContent = "Calculating...";
});
// Receive result from worker
worker.onmessage = function(event) {
output.textContent = "Result: " + event.data;
};
</script>
Explanation:
worker.postMessage()
sends data from the main thread to the worker.
self.onmessage
in the worker receives the data.
self.postMessage()
sends the result back.
worker.onmessage
in the main thread handles the response.
The main thread remains responsive while the calculation runs in the background.
You can stop a worker when it’s no longer needed using terminate()
.
worker.terminate(); // Stops the worker immediately
Tip: Always terminate workers after use to free system resources.
You can listen for errors using onerror
.
worker.onerror = function(event) {
console.error("Worker error:", event.message);
};
Explanation:
event.message
shows the error message.
event.filename
shows the script where the error occurred.
event.lineno
shows the line number.
Web Workers are ideal for long loops, complex calculations, or data processing.
worker.js
self.onmessage = function(event) {
const n = event.data;
let factorial = 1;
for(let i = 2; i <= n; i++) {
factorial *= i;
}
self.postMessage(factorial);
};
main.js
const worker = new Worker("worker.js");
worker.onmessage = function(event) {
console.log("Factorial result:", event.data);
};
worker.postMessage(10); // Calculate factorial of 10
The calculation runs without freezing the main page.
Communication between main thread and worker is always via message passing.
Main to Worker: worker.postMessage(data)
Worker to Main: self.postMessage(data)
Example:
// main.js
worker.postMessage({ type: "greet", name: "Vicky" });
// worker.js
self.onmessage = function(event) {
const data = event.data;
if(data.type === "greet") {
self.postMessage("Hello, " + data.name + "!");
}
};
Explanation:
You can send objects or strings between main thread and worker.
Workers don’t share memory with the main thread.
No DOM access – cannot manipulate HTML elements directly.
Limited API access – workers cannot use some browser features like alert()
or document
.
Communication overhead – sending large data back and forth can be slower.
Same-origin policy – worker scripts must be on the same domain or server.
Despite these limitations, Web Workers significantly improve performance for heavy tasks.
Calculating large datasets in the background.
Image or video processing in the browser.
Real-time games or simulations.
Performing AI or machine learning tasks on the client side.
Fetching and processing data from APIs without freezing UI.
The Web Worker API is a powerful tool to run background tasks in JavaScript. Key points to remember:
Use Worker()
to create a new worker.
Communicate using postMessage()
and onmessage
.
Terminate workers with terminate()
when done.
Handle errors using onerror
.
Web Workers cannot access the DOM directly, but they keep your UI responsive.
Mastering Web Workers allows you to build fast, smooth, and interactive web applications, even for heavy computations or real-time tasks.
Create a Web Worker that calculates the sum of numbers from 1 to a user-entered value and sends the result back to the main thread.
Write a script that calculates the factorial of a number using a Web Worker without freezing the main page.
Implement a Web Worker that reverses a long string sent from the main thread and returns the reversed string.
Create a worker that counts the number of vowels in a given text input and sends the count back to the main thread.
Write code to terminate a Web Worker after it finishes processing a large array of numbers.
Implement a Web Worker that multiplies each element in an array by 2 and returns the new array to the main thread.
Create a worker that generates a random large array of numbers and calculates the maximum value, sending the result to the main thread.
Write a script where the main thread sends an object containing {name, age}
to a worker, and the worker responds with a greeting message.
Implement error handling in a Web Worker that divides two numbers and returns a message if division by zero occurs.
Create a Web Worker that simulates a countdown timer from a given number and posts the remaining seconds back to the main thread at 1-second intervals.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts