HTML Web Workers
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.
Why Use Web Workers?
When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker allows you to run long-running scripts in a separate thread, allowing the main user interface to remain responsive. This is ideal for computationally intensive tasks like complex calculations, data processing, or fetching large amounts of data.
Example: Web Worker
In this example, a web worker counts numbers in the background and posts the result back to the main page.
javascript
// main.js
if (typeof(Worker) !== "undefined") {
let w = new Worker("demo_workers.js");
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
}
// demo_workers.js
let i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();Test Yourself with an Exercise
What is the primary benefit of using a Web Worker?