We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 90 – JavaScript Web Workers

Web Workers allow JavaScript to run in the background, on a separate thread from the main execution thread. This helps prevent UI freezing, especially during heavy computations or data processing.


What are Web Workers?

  • JavaScript is single-threaded by default.
  • Web Workers run scripts in background threads, separate from the main UI thread.
  • Useful for tasks like:
    • Heavy computations
    • Parsing large files
    • Processing data without blocking UI

When to Use Web Workers

  • Long loops or expensive calculations
  • Repeated or concurrent data processing
  • Keeping UI responsive during background tasks

Creating a Web Worker

  1. Create a separate JavaScript file for the worker (e.g. worker.js)
  2. In your main script, use the Worker() constructor to run it.

worker.js

// This code runs in the background
self.onmessage = function(e) {
  console.log('Worker received:', e.data);
  let result = e.data * 2;
  self.postMessage(result);
};

main.js

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

worker.postMessage(10); // Send data to worker

worker.onmessage = function(e) {
  console.log('Result from worker:', e.data);
};

Limitations

  • Workers cannot manipulate the DOM directly.
  • They have a separate scope from the main thread.
  • You must communicate using postMessage.

Try Your Hand

  1. Create a simple HTML page.
  2. Set up a Web Worker to simulate a long task (like a loop).
  3. Display a message once the task is complete.

Summary

Feature Description
Background Execution Workers run tasks in a separate thread
Communication Via postMessage and onmessage
Use Cases Data processing, image manipulation, etc.
Limitation Cannot access DOM directly