-
Hajipur, Bihar, 844101
Web Workers allow you to run JavaScript scripts in background threads separate from the main execution thread of a web page. This helps in performing heavy computations without freezing or slowing down the user interface.
Perform CPU-intensive tasks without blocking the UI
Improve responsiveness and user experience
Run multiple scripts in parallel
You create a Web Worker by specifying a JavaScript file that runs in the background.
const worker = new Worker('worker.js');
worker.postMessage('Hello Worker');
worker.onmessage = function(event) {
console.log('Message from worker:', event.data);
};
onmessage = function(event) {
const result = event.data + ' - processed in worker';
postMessage(result);
};
Main thread → Worker: Use worker.postMessage(data)
Worker → Main thread: Use postMessage(data)
Listening for messages: Use onmessage
event handler
To stop a worker when it’s no longer needed:
worker.terminate();
index.html
<button id="start">Start Worker</button>
<p id="output"></p>
<script>
const worker = new Worker('worker.js');
worker.onmessage = function(e) {
document.getElementById('output').innerText = e.data;
};
document.getElementById('start').onclick = function() {
worker.postMessage('Start processing');
};
</script>
worker.js
onmessage = function(e) {
// Perform a heavy calculation (simulate with loop)
let count = 0;
for(let i = 0; i < 1e7; i++) {
count += i;
}
postMessage('Processing done: ' + count);
};
Q1. Create a Web Worker that calculates the sum of numbers from 1 to 1,000,000 without blocking UI.
Q2. Send a message from main script to worker and display the response.
Q3. Terminate the Web Worker after the task is completed.
Q4. Create a worker to perform factorial calculation of a given number.
Q5. Implement error handling in Web Worker using onerror
.
Q6. Pass an array to the worker and receive the squared values array.
Q7. Create multiple workers to run parallel computations.
Q8. Use worker.terminate()
to stop workers on button click.
Q9. Use postMessage()
to send complex data objects between main script and worker.
Q10. Demonstrate how Web Workers improve UI responsiveness by comparing with synchronous code.
Q1: What is the main benefit of Web Workers?
Q2: How do you create a Web Worker?
Q3: How does the main script send data to the worker?
Q4: How does the worker send data back to the main script?
Q5: Which method stops a Web Worker?
Q6: How do you listen for messages from a worker?
Q7: What is the file format for a Web Worker script?
Q8: Which of the following is NOT allowed inside Web Workers?