Ask any question about JavaScript here... and get an instant response.
How can I use a web worker to keep my UI responsive while processing large data in JavaScript?
Asked on Dec 14, 2025
Answer
Web Workers allow you to run JavaScript in the background, separate from the main UI thread, which helps keep your UI responsive during intensive tasks. Here's a basic example of how to use a Web Worker to process large data.
<!-- BEGIN COPY / PASTE -->
// main.js
const worker = new Worker('worker.js');
worker.onmessage = function(e) {
console.log('Processed data:', e.data);
};
const largeData = [/* large data array */];
worker.postMessage(largeData);
// worker.js
onmessage = function(e) {
const data = e.data;
// Simulate data processing
const processedData = data.map(item => item * 2);
postMessage(processedData);
};
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "main.js" file initializes a new Worker with "worker.js".
- Use "worker.postMessage()" to send data to the worker.
- In "worker.js", use "onmessage" to receive data and "postMessage()" to send processed data back.
- This setup allows data processing in the background, keeping the UI responsive.
Recommended Links:
