patternjavascriptModeratepending
JavaScript Web Workers for CPU-intensive tasks
Viewed 0 times
web workermain threadoffloadpostMessageshared array buffer
Problem
CPU-intensive operations (image processing, data parsing, calculations) block the main thread and freeze the UI.
Solution
Offload heavy work to Web Workers:
// worker.js
self.addEventListener('message', (event) => {
const { data, type } = event.data;
if (type === 'process') {
// Heavy computation runs off main thread
const result = heavyComputation(data);
self.postMessage({ type: 'result', result });
}
});
function heavyComputation(data) {
// This would freeze the UI on main thread
return data.map(item => complexTransform(item));
}// main.js
const worker = new Worker('worker.js');
// Promise-based wrapper
function runInWorker(data) {
return new Promise((resolve, reject) => {
worker.onmessage = (e) => resolve(e.data.result);
worker.onerror = (e) => reject(e);
worker.postMessage({ type: 'process', data });
});
}
// Usage
const result = await runInWorker(largeDataset);
// Inline worker (no separate file)
const blob = new Blob([`
self.onmessage = (e) => {
const result = e.data.reduce((a, b) => a + b, 0);
self.postMessage(result);
};
`], { type: 'application/javascript' });
const inlineWorker = new Worker(URL.createObjectURL(blob));
// Cleanup
worker.terminate();Why
The main thread handles UI rendering, event handling, and user interaction. Any operation taking more than ~16ms causes visible jank.
Gotchas
- Workers cannot access the DOM
- Data is copied (not shared) via postMessage by default - use SharedArrayBuffer for shared memory
- Workers have overhead - don't use for trivial operations
Context
Web applications with CPU-intensive operations
Revisions (0)
No revisions yet.