Clean β’ Professional
The Web Workers API allows JavaScript to run in the background without blocking the main page.
Normally, JavaScript runs on a single thread (the main thread). If a heavy task is running (like a large loop), it can freeze the UI. Web Workers solve this problem by moving such tasks to a background thread, keeping the web page smooth and responsive.
Example:
Without Web Workers, if you run a loop with millions of iterations, your webpage may hang. With Web Workers, the loop runs in the background, and the user can still scroll or click buttons smoothly.
postMessage and onmessage).This means:
A Web Worker needs a separate JavaScript file.
Example:
main.js
// Create a new worker
let worker = new Worker("worker.js");
// Send message to worker
worker.postMessage("Start the calculation");
// Receive message from worker
worker.onmessage = function(event) {
console.log("Result from worker: " + event.data);
};worker.js
// Worker code (runs in background)
onmessage = function(event) {
console.log("Worker received: " + event.data);
let sum = 0;
for (let i = 0; i < 1000000000; i++) {
sum += i;
}
// Send result back
postMessage(sum);
};postMessage() β send data.onmessage β receive data.Example: Sending and receiving a message
// main.js
worker.postMessage("Hello Worker!");
// worker.js
onmessage = function(e) {
postMessage("Hello Main Script, I got your message: " + e.data);
};Workers keep running in the background until you manually stop them.
worker.terminate();Errors inside workers donβt crash the main thread. You can catch them using onerror.
Example:
worker.onerror = function(e) {
console.log("Error in worker: " + e.message);
};document, window, etc. are not available).Always check compatibility before using:
if (window.Worker) {
console.log("Web Workers are supported!");
} else {
console.log("Sorry, your browser doesn't support Web Workers.");
}Β