Tips and Tricks #108: Use Web Workers for Heavy Computations

Move CPU-intensive tasks off the main thread to keep the UI responsive.

Code Snippet

// worker.js
self.onmessage = function(e) {
  const result = heavyComputation(e.data);
  self.postMessage(result);
};

function heavyComputation(data) {
  // Expensive operation that would block UI
  return data.reduce((acc, val) => acc + Math.sqrt(val), 0);
}

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

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

// Send data to worker (non-blocking)
worker.postMessage(largeDataArray);

Why This Helps

  • Keeps UI responsive during heavy computation
  • Utilizes additional CPU cores
  • Prevents ‘page unresponsive’ warnings

How to Test

  • Compare UI responsiveness with/without worker
  • Monitor main thread blocking in DevTools Performance

When to Use

Data parsing, image processing, complex calculations, any task taking >50ms.

Performance/Security Notes

Workers can’t access DOM. Use transferable objects for large data to avoid copying overhead.

References


Try this tip in your next project and share your results in the comments!


Discover more from Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.