Skip to the code

Batch layout reads and writes

Code all over the tea shop reads layout (offsetWidth, getBoundingClientRect()) and writes styles. When a read comes right after a write in the same task, the browser has to lay the page out there and then to answer it, a forced synchronous layout, and a loop that alternates reads and writes lays the page out on every pass. Write measure(read) and mutate(write), which queue a read and a write instead of running them, the way the FastDOM library does.

The first call asks for an animation frame, and calls made before that frame join it, so a batch needs one requestAnimationFrame. In the frame, run every queued read, in the order they were queued, then every queued write, in order. A read queued by a read, and a write queued by a read or a write, run in this frame too. A read queued by a write waits for the next frame, which it asks for, so no read in a frame comes after a write.

Both return a handle. clear(handle) takes that task out of the queue and returns true, or returns false when the task isn't waiting (it already ran, or was cleared).

for (const card of teaCards) {
  measure(() => {
    const width = card.offsetWidth;
    mutate(() => (card.style.height = width * 0.75 + "px"));
  });
}
// In the next frame: every read, then every write. The page is laid out once.

What the tests check

  1. runs nothing until the frame, then every read before any write
    const clock = useFakeTimers();
    const log = [];
    measure(() => log.push("read 1 at " + clock.now()));
    mutate(() => log.push("write 1 at " + clock.now()));
    measure(() => log.push("read 2 at " + clock.now()));
    mutate(() => log.push("write 2 at " + clock.now()));
    expect(log).toEqual([]);
    await clock.runAllAsync();
    expect(log).toEqual(["read 1 at 16", "read 2 at 16", "write 1 at 16", "write 2 at 16"]);
    
  2. asks for one frame per batch
    const clock = useFakeTimers();
    let frames = 0;
    const realFrame = requestAnimationFrame;
    globalThis.requestAnimationFrame = (callback) => {
      frames += 1;
      return realFrame(callback);
    };
    for (let index = 0; index < 5; index++) {
      measure(() => {});
      mutate(() => {});
    }
    await clock.runAllAsync();
    expect(frames).toBe(1);
    let ranAt = null;
    measure(() => (ranAt = clock.now()));
    await clock.runAllAsync();
    expect(frames).toBe(2);
    expect(ranAt).toBe(32);
    
  3. sizes the cards with no forced layout
    const clock = useFakeTimers();
    const cards = Array.from(document.querySelectorAll(".card"));
    const layout = trackLayout(cards);
    cards.forEach((card, index) => layout.size(card, { width: 200 + index * 40 }));
    for (const card of cards) {
      measure(() => {
        const width = card.offsetWidth;
        mutate(() => (card.style.height = width * 0.75 + "px"));
      });
    }
    await clock.runAllAsync();
    expect(cards.map((card) => card.style.height)).toEqual(["150px", "180px", "210px"]);
    expect(layout.log).toEqual(["read", "read", "read", "write", "write", "write"]);
    expect(layout.forcedReflows()).toBe(0);
    
  4. tasks queued during the frame: reads from a write wait for the next frame, the rest run now
    const clock = useFakeTimers();
    const log = [];
    mutate(() => {
      log.push("write at " + clock.now());
      measure(() => log.push("read from a write at " + clock.now()));
      mutate(() => log.push("write from a write at " + clock.now()));
    });
    measure(() => {
      log.push("read at " + clock.now());
      measure(() => log.push("read from a read at " + clock.now()));
      mutate(() => log.push("write from a read at " + clock.now()));
    });
    await clock.runAllAsync();
    expect(log).toEqual([
      "read at 16",
      "read from a read at 16",
      "write at 16",
      "write from a read at 16",
      "write from a write at 16",
      "read from a write at 32",
    ]);
    
  5. a layout read queued by a write doesn't force a layout
    const clock = useFakeTimers();
    const [card] = document.querySelectorAll(".card");
    const layout = trackLayout(card);
    layout.size(card, { width: 240 });
    let width = null;
    mutate(() => {
      card.style.width = "240px";
      measure(() => (width = card.offsetWidth));
    });
    await clock.runAllAsync();
    expect(width).toBe(240);
    expect(layout.forcedReflows()).toBe(0);
    
  6. clear takes a waiting task out of the queue
    const clock = useFakeTimers();
    const log = [];
    const read = measure(() => log.push("read"));
    const write = mutate(() => log.push("write"));
    measure(() => log.push("other read"));
    expect(clear(read)).toBe(true);
    expect(clear(read)).toBe(false);
    const kept = mutate(() => log.push("kept write"));
    expect(clear(write)).toBe(true);
    await clock.runAllAsync();
    expect(log).toEqual(["other read", "kept write"]);
    expect(clear(kept)).toBe(false);
    

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).