LearnFrenzy
Sign in Take a free test

Event Loop · Event Loop Coding Problems · Question 2

Process a large array in chunks without blocking in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links