Middle
A array of 2 million elements arrives, each element needs to be processed for 100 milliseconds. Interaction with the server cannot be changed. How to process this array so as not to block the UI?
sobes.tech AI
Answer from AI
To process a large array with long processing of each element without blocking the UI, you need to break the work into small parts and execute them asynchronously, allowing the browser to update the interface between batches.
An example approach using setTimeout or requestIdleCallback:
function processChunk(array, start, chunkSize) {
const end = Math.min(start + chunkSize, array.length);
for (let i = start; i < end; i++) {
// Processing element, takes ~100ms
processElement(array[i]);
}
if (end < array.length) {
setTimeout(() => processChunk(array, end, chunkSize), 0);
}
}
processChunk(largeArray, 0, 10); // process 10 elements at a time
This way, the UI will not freeze, as time is given for rendering and event processing between batches.
If a Web Worker is available, processing can be offloaded there to avoid blocking the main thread.