Senior
How can you render a thousand elements without freezing the browser, using knowledge of the Event Loop?
sobes.tech AI
Answer from AI
To render a thousand elements without freezing the browser, you can split the rendering into small parts and execute them asynchronously using the Event Loop. This allows the browser to handle user events and update the interface between rendering batches.
One approach is to use requestIdleCallback or setTimeout for incremental addition of elements:
const container = document.getElementById('list');
const items = new Array(1000).fill(null).map((_, i) => `Element ${i + 1}`);
function renderChunk(start, chunkSize) {
const end = Math.min(start + chunkSize, items.length);
for (let i = start; i < end; i++) {
const div = document.createElement('div');
div.textContent = items[i];
container.appendChild(div);
}
if (end < items.length) {
// Delayed call for the next part
setTimeout(() => renderChunk(end, chunkSize), 0);
}
}
renderChunk(0, 50); // Render 50 elements at a time
This way, the browser is not blocked, as the Event Loop can process other tasks, such as user events or re-rendering, between rendering batches.