Process 10 records in chunks of 4, yielding to the event loop between chunks with setTimeout, and show that a "click" task scheduled at the start runs between chunks.
Solution
main.js
function processInChunks(items, size, handle, done) {
let index = 0;
function nextChunk() {
const end = Math.min(index + size, items.length);
for (; index < end; index++) handle(items[index]);
console.log(`chunk done (${index}/${items.length})`);
if (index < items.length) setTimeout(nextChunk, 0); // give other tasks a turn
else done();
}
nextChunk();
}
const records = Array.from({ length: 10 }, (_, i) => i + 1);
let sum = 0;
setTimeout(() => console.log(" ↳ user click handled"), 0);
processInChunks(records, 4, (r) => (sum += r), () => console.log("all done, sum =", sum));
Output Verified by running it on Node.js
chunk done (4/10)
↳ user click handled
chunk done (8/10)
chunk done (10/10)
all done, sum = 55
Each chunk is one task. The click task was queued before the second chunk, so it runs in between – the page stays responsive during long work.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!