Challenge 2: Chunk a Long-Running Function — Possible Solution ==================================================================== // Original, blocking version: // function processAll(items) { // for (const item of items) { expensiveWork(item); } // } function processInChunks(items, i = 0) { const end = Math.min(i + 100, items.length); // 100 items per chunk for (; i < end; i++) { expensiveWork(items[i]); } if (i < items.length) { setTimeout(() => processInChunks(items, i), 0); // yield, then resume } } // Usage: processInChunks(the5000Items); WHY THIS WORKS -------------- - This follows the exact same structural pattern as the chapter's own processInChunks example, just with the chunk size changed from 50 to 100 (per this challenge's requirement) and the total item count changed from an unspecified size to 5,000. - Math.min(i + 100, items.length) computes the END index for THIS chunk, capping it at the actual array length so the last chunk doesn't try to read past the end of the array — with 5,000 items and a chunk size of 100, this produces exactly 50 chunks total (5000 / 100). - The inner for loop processes only the current 100-item slice (items[i] through items[end-1]) before the function returns control back to the browser — this is the critical difference from the blocking version, which processes all 5,000 items in one single, uninterrupted pass with no opportunity for the browser to do anything else in between. - setTimeout(() => processInChunks(items, i), 0) schedules the NEXT chunk to run on a fresh turn of the event loop, passing along the updated starting index i (now pointing at the first item NOT yet processed) — this is what actually "yields," since a setTimeout callback, even with a 0ms delay, waits for the current call stack to fully unwind and lets the browser process any pending input or paint before the next chunk begins. - The recursive-looking structure (processInChunks calling itself via setTimeout rather than looping directly) is precisely what breaks one 300ms+ long task into 50 much shorter tasks, each well under the chapter's 50ms long-task threshold if expensiveWork per item is reasonably fast — giving the browser many small windows to remain responsive throughout the whole 5,000-item operation instead of one large window where it's completely blocked.