What are Web Workers and how are they related to asynchronicity?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Hard
#JavaScript #Asynchronicity

Brief Answer

Web Workers are a mechanism in JavaScript that allows scripts to run in a background thread, separate from the main user interface thread. They enable heavy computations to be performed without blocking the interface, ensuring smooth application performance. Web Workers are related to asynchronicity because they represent a separate execution thread that communicates with the main thread through a message system.

Key features:

  • Parallel execution — code runs in a separate thread
  • Isolation — no access to DOM, window, and other main thread objects
  • Asynchronous communication — data exchange through postMessage/onmessage

Full Answer

Web Workers are a standard browser API that allows JavaScript code to run in separate threads without blocking the main user interface thread. This is particularly important for performing heavy computations, processing large amounts of data, or executing long-running operations.

How Web Workers Work

Web Workers create a separate execution thread that can work in parallel with the main thread:

// Creating a Web Worker
const worker = new Worker('worker.js');
 
// Sending data to worker
worker.postMessage({ data: 'Hello' });
 
// Receiving data from worker
worker.onmessage = function(e) {
  console.log('Result:', e.data);
};

Main Types of Web Workers

1. Dedicated Workers

Created for a specific page and accessible only to it:

const worker = new Worker('dedicated-worker.js');

2. Shared Workers

Can be used by multiple tabs or frames:

const worker = new SharedWorker('shared-worker.js');

3. Service Workers

Used for intercepting network requests and caching:

// Registering Service Worker
navigator.serviceWorker.register('service-worker.js');

Relationship to Asynchronicity

Web Workers are closely related to asynchronicity but differ from traditional asynchronous operations:

  1. Parallelism — workers execute in parallel with the main thread
  2. Isolation — they don’t have access to DOM and many main thread APIs
  3. Messaging — data exchange happens asynchronously through messages

Practical Examples

Computations without blocking UI

// Main thread
const worker = new Worker('calculator.js');
 
worker.postMessage({ 
  operation: 'factorial', 
  number: 1000 
});
 
worker.onmessage = function(e) {
  console.log('Result:', e.data);
};

Processing large data

// Web Worker
self.onmessage = function(e) {
  const data = e.data;
  // Heavy data processing
  const result = processLargeData(data);
  self.postMessage(result);
};

Web Workers Limitations

1. No DOM access

// ❌ This doesn't work in Web Worker
document.getElementById('element');
 
// ✅ Only through messages
self.postMessage(result);

2. Limited APIs

  • No access to window, document, parent
  • No access to DOM APIs
  • No access to some web APIs

Common Mistakes

1. Attempting DOM access

// ❌ Error in Web Worker
document.querySelector('.element');
 
// ✅ Correct approach
self.importScripts('utils.js');

2. Passing functions

// ❌ Cannot pass functions
worker.postMessage({ 
  callback: function() { } 
});
 
// ✅ Pass data, handle in worker
worker.postMessage({ 
  action: 'process', 
  data: someData 
});

Best Practices

  1. Use for heavy computations — don’t block the main thread
  2. Transfer only necessary data — minimize message volume
  3. Terminate workers — free resources after use
  4. Handle errors — use onerror to catch exceptions
  5. Use transferable objects — for efficient large data transfer

Compatibility

Web Workers are supported by all modern browsers. Polyfills or alternative solutions are required for older browsers.

Key Web Workers Benefits

  1. Non-blocking computations — smooth UI during heavy operations
  2. Parallelism — utilization of multiple CPU cores
  3. Isolation — protection of main thread from crashes
  4. Performance — efficient data processing
  5. Scalability — ability to create multiple workers

Web Workers are a powerful tool for asynchronous computations, allowing efficient use of multithreading in the browser and ensuring smooth user interface performance even during heavy operations.


Knowledge Check Task

Task

What’s the difference between Web Workers and traditional asynchronous operations (Promise, async/await)?

// Traditional asynchronous code
async function fetchData() {
  const response = await fetch('/api/data');
  return response.json();
}
 
// Web Worker
const worker = new Worker('worker.js');
worker.postMessage({ action: 'calculate' });
View answer

Answer: Key differences between Web Workers and traditional asynchronous operations:

  1. Execution thread:

    • Asynchronous operations (Promise, async/await) execute in the main thread but don’t block it
    • Web Workers execute in completely separate threads
  2. Task type:

    • Asynchronous operations are mainly for I/O (network requests, timers, events)
    • Web Workers are for CPU-intensive tasks (computations, data processing)
  3. Resource access:

    • Asynchronous operations have full access to DOM and browser APIs
    • Web Workers are isolated and don’t have access to DOM
  4. Communication:

    • Asynchronous operations return Promises that resolve with results
    • Web Workers exchange data through a message system (postMessage)
  5. Performance:

    • Asynchronous operations don’t require additional resources for thread creation
    • Web Workers require overhead for thread creation and management but can perform parallel computations

Web Workers are suitable for heavy computations when you need to maintain interface responsiveness, while traditional asynchronous operations are better for working with external resources.


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪