A Web Worker is a JavaScript API that allows you to run a script operation in the background, separate from the main execution thread of a web page. This allows for long-running scripts to be executed without freezing the user interface, making the page more responsive. Web Workers can be used for tasks such as image or video processing, or for creating complex animations, without negatively impacting the performance of the page. Web Workers are supported in most modern web browsers.
Example of Web Worker In JavaScript
Here’s an example of how to use a Web Worker in JavaScript:
// worker.js
self.addEventListener('message', (e) => {
const data = e.data;
// do some time-consuming operation
const result = heavyComputation(data);
self.postMessage(result);
});
// main.js
const worker = new Worker('worker.js');
worker.addEventListener('message', (e) => {
console.log(e.data);
});
worker.postMessage({data: 'hello'});
In this example, we have two files: worker.js and main.js. worker.js is the script that will be run in the background by the Web Worker. It listens for a message event, which is sent from the main script. It receives the data sent by the main script, does some time-consuming operation on it and then sends the result back to the main script using self.postMessage(result).
main.js creates a new instance of the Worker object, passing in the path to the worker.js script. It then listens for message events, which will be sent by the worker when the computation is complete. It sends the data to the worker using worker.postMessage({data: ‘hello’}).
This way, the heavy computation is not blocking the main thread, and the web page remains responsive.
Also Read:
- How To Sort an Array of Strings In JavaScript?
- ECMAScript vs JavaScript
- What Is Strict Mode In JavaScript?
- Arrow Functions In JavaScript
- Difference Between Node.js and AngularJS With Example
- Difference Between == And === In JavaScript
- What Is JSON In JavaScript
- How To Go Back To Previous Page In JavaScript?
- How To Detect A Mobile Device With JavaScript?
- How To Close The Current Tab In A Browser Window Using JavaScript?
- How To Convert Input Text To Uppercase While Typing Using JavaScript?
- How To Show A Confirmation Message Before Delete In JavaScript?
- How To Detect Browser or Tab Closing In JavaScript?
- How To Get Hash Value From URL Using JavaScript?
- How To Get The Name, Size, And Type Of A File In JavaScript?
- Run JavaScript From The Command Line