JavaScript·Advanced·Coding·1 min read
How would you yield during a large browser computation?
Short interview answer
Break work into bounded chunks and schedule continuation through a task-producing mechanism or an appropriate scheduling API so rendering and input can run between chunks. A chain of queueMicrotask calls does not yield to rendering because microtasks drain before the next rendering opportunity.
Example
async function processInChunks(items, work, chunkSize = 500) { for (let i = 0; i < items.length; i += chunkSize) { for (let j = i; j < i + chunkSize && j < items.length; j++) work(items[j]); // hand the thread back so the browser can paint / handle input await new Promise((r) => setTimeout(r)); }}Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.