Skip to the code

Process in chunks

The tea shop's reviews page scores every review, and with thousands of them one loop is a long task: until it ends, the page can't respond to a tap or paint anything. Write processInChunks(items, work, options), an async function that calls work(item, index) for every item, in order, and resolves with an array of what each call returned.

Keep each piece of work short. Before each item, if options.budget ms (50 when it isn't given) or more have passed since you started or last yielded, yield to the browser first, then start timing again. Read the time with performance.now().

Yield with scheduler.yield() where the browser has it, and with a 0 ms setTimeout where it doesn't: some browsers have no scheduler at all, and some have scheduler.postTask() but not scheduler.yield(). If work throws, the promise rejects with that error, and no later item runs.

const scores = await processInChunks(reviews, (review) => scoreReview(review.text));
// The scores come back in the reviews' order. Every 50 ms or so the loop stops,
// so the browser can handle a tap and paint, and then it carries on.

What the tests check

  1. calls work for every item in order, with its index, and resolves with the results
    const clock = useFakeTimers();
    const seen = [];
    const done = processInChunks(["green", "black", "oolong"], (tea, index) => {
      clock.spend(5);
      seen.push(index + ":" + tea);
      return tea.toUpperCase();
    });
    await clock.runAllAsync();
    expect(await done).toEqual(["GREEN", "BLACK", "OOLONG"]);
    expect(seen).toEqual(["0:green", "1:black", "2:oolong"]);
    
  2. stops for the browser once 50 ms have passed
    const clock = useFakeTimers();
    const done = [];
    const finished = processInChunks([1, 2, 3, 4, 5], (n) => {
      clock.spend(20);
      done.push(n);
    });
    // 60 ms of work: it yields before the fourth item.
    expect(done).toEqual([1, 2, 3]);
    await clock.runAllAsync();
    await finished;
    expect(done).toEqual([1, 2, 3, 4, 5]);
    
  3. starts timing again after each break
    const clock = useFakeTimers();
    const pieces = [[]];
    const realYield = scheduler.yield.bind(scheduler);
    scheduler.yield = () => {
      pieces.push([]);
      return realYield();
    };
    const finished = processInChunks([1, 2, 3, 4, 5, 6, 7], (n) => {
      clock.spend(20);
      pieces[pieces.length - 1].push(n);
    });
    await clock.runAllAsync();
    await finished;
    expect(pieces).toEqual([[1, 2, 3], [4, 5, 6], [7]]);
    
  4. a quick list finishes in one task, without yielding
    const clock = useFakeTimers();
    let yields = 0;
    const realYield = scheduler.yield.bind(scheduler);
    scheduler.yield = () => {
      yields += 1;
      return realYield();
    };
    const results = await processInChunks([1, 2, 3, 4], (n) => {
      clock.spend(10);
      return n * 2;
    });
    expect(results).toEqual([2, 4, 6, 8]);
    expect(yields).toBe(0);
    
  5. yields with scheduler.yield() where the browser has it
    const clock = useFakeTimers();
    const used = { yield: 0, timeout: 0 };
    const realYield = scheduler.yield.bind(scheduler);
    scheduler.yield = () => {
      used.yield += 1;
      return realYield();
    };
    const realTimeout = setTimeout;
    globalThis.setTimeout = (fn, ms, ...rest) => {
      used.timeout += 1;
      return realTimeout(fn, ms, ...rest);
    };
    const finished = processInChunks([1, 2, 3], () => clock.spend(60));
    await clock.runAllAsync();
    await finished;
    expect(used.yield).toBeGreaterThan(0);
    expect(used.timeout).toBe(0);
    
  6. falls back to a 0 ms timeout where there's no scheduler
    const clock = useFakeTimers({ scheduler: false });
    const delays = [];
    const realTimeout = setTimeout;
    globalThis.setTimeout = (fn, ms, ...rest) => {
      delays.push(Number(ms) || 0);
      return realTimeout(fn, ms, ...rest);
    };
    const done = [];
    const finished = processInChunks([1, 2, 3], (n) => {
      clock.spend(60);
      done.push(n);
    });
    expect(done).toEqual([1]);
    await clock.runAllAsync();
    await finished;
    expect(done).toEqual([1, 2, 3]);
    expect(delays.length).toBeGreaterThan(0);
    expect(delays.every((ms) => ms === 0)).toBe(true);
    
  7. falls back too where scheduler has postTask() but no yield()
    const clock = useFakeTimers();
    globalThis.scheduler = { postTask: scheduler.postTask.bind(scheduler) };
    let timeouts = 0;
    const realTimeout = setTimeout;
    globalThis.setTimeout = (fn, ms, ...rest) => {
      timeouts += 1;
      return realTimeout(fn, ms, ...rest);
    };
    const finished = processInChunks([1, 2, 3], () => clock.spend(60));
    await clock.runAllAsync();
    expect((await finished).length).toBe(3);
    expect(timeouts).toBeGreaterThan(0);
    
  8. takes another budget
    const clock = useFakeTimers();
    const pieces = [[]];
    const realYield = scheduler.yield.bind(scheduler);
    scheduler.yield = () => {
      pieces.push([]);
      return realYield();
    };
    const finished = processInChunks([1, 2, 3, 4, 5], (n) => {
      clock.spend(30);
      pieces[pieces.length - 1].push(n);
    }, { budget: 100 });
    await clock.runAllAsync();
    await finished;
    expect(pieces).toEqual([[1, 2, 3, 4], [5]]);
    
  9. an error in work rejects the promise, and no later item runs
    const clock = useFakeTimers();
    const done = [];
    const outcome = processInChunks([1, 2, 3, 4], (n) => {
      clock.spend(30);
      if (n === 3) throw new Error("This review has no text");
      done.push(n);
    }).then(
      () => "resolved",
      (error) => error.message,
    );
    await clock.runAllAsync();
    expect(await outcome).toBe("This review has no text");
    expect(done).toEqual([1, 2]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).