HTML Web Workers


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.


🔹 Why Use Web Workers?

  • Perform CPU-intensive tasks without blocking the UI

  • Improve responsiveness and user experience

  • Run multiple scripts in parallel


🔹 Creating a Web Worker

You create a Web Worker by specifying a JavaScript file that runs in the background.

Example: main.js
const worker = new Worker('worker.js');

worker.postMessage('Hello Worker');

worker.onmessage = function(event) {
  console.log('Message from worker:', event.data);
};
Example: worker.js
onmessage = function(event) {
  const result = event.data + ' - processed in worker';
  postMessage(result);
};

🔹 Communication between Main Thread and Worker

  • Main thread → Worker: Use worker.postMessage(data)

  • Worker → Main thread: Use postMessage(data)

  • Listening for messages: Use onmessage event handler


🔹 Terminating a Worker

To stop a worker when it’s no longer needed:

worker.terminate();

💻 Example: Simple Worker Usage

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);
};

Practice Questions

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.


HTML Web Workers Quiz

Q1: What is the main benefit of Web Workers?

A. Faster HTML rendering
B. Running scripts in background without blocking UI
C. Better CSS styling
D. Easier HTML structure

Q2: How do you create a Web Worker?

A. new Worker('script.js')
B. new Thread('script.js')
C. new Background('script.js')
D. new Process('script.js')

Q3: How does the main script send data to the worker?

A. worker.send()
B. worker.postMessage()
C. worker.message()
D. worker.transmit()

Q4: How does the worker send data back to the main script?

A. postMessage()
B. sendMessage()
C. worker.send()
D. worker.reply()

Q5: Which method stops a Web Worker?

A. worker.stop()
B. worker.kill()
C. worker.terminate()
D. worker.close()

Q6: How do you listen for messages from a worker?

A. worker.onmessage = function(event){}
B. worker.onreceive = function(event){}
C. worker.receive = function(event){}
D. worker.ondata = function(event){}

Q7: What is the file format for a Web Worker script?

A. JSON
B. JS (JavaScript)
C. HTML
D. CSS

Q8: Which of the following is NOT allowed inside Web Workers?

A. XMLHttpRequest
B. DOM manipulation
C. Timers (setTimeout)
D. Mathematical calculations

Go Back Top