javascript
49 lines · 8 steps
Batching DOM reads and writes to avoid layout thrash
A scheduler groups all DOM measurements before mutations in a single animation frame to prevent forced reflows.
Explained by
highlit
1class DOMBatcher {
2 constructor() {
3 this.reads = [];
4 this.writes = [];
5 this.scheduled = false;
6 }
7
8 read(task) {
9 this.reads.push(task);
10 this.schedule();
11 }
12
13 write(task) {
14 this.writes.push(task);
15 this.schedule();
16 }
17
18 schedule() {
19 if (this.scheduled) return;
20 this.scheduled = true;
21 requestAnimationFrame(() => this.flush());
22 }
23
24 flush() {
25 const reads = this.reads;
26 const writes = this.writes;
27 this.reads = [];
28 this.writes = [];
29 this.scheduled = false;
30
31 const results = reads.map((task) => task());
32 writes.forEach((task, i) => task(results[i]));
33
34 if (this.reads.length || this.writes.length) {
35 this.schedule();
36 }
37 }
38}
39
40export const batcher = new DOMBatcher();
41
42export function equalizeHeights(elements) {
43 batcher.read(() => Math.max(...elements.map((el) => el.offsetHeight)));
44 batcher.write((maxHeight) => {
45 for (const el of elements) {
46 el.style.height = `${maxHeight}px`;
47 }
48 });
49}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Interleaving DOM reads and writes forces the browser to recompute layout repeatedly, so grouping them by phase eliminates that cost.
- 2A scheduled flag ensures many enqueued tasks collapse into a single requestAnimationFrame callback instead of one per call.
- 3Passing read results into write callbacks lets mutations depend on measurements taken safely before any writes happen.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/batching-dom-reads-and-writes-to-avoid-layout-thrash-explained-javascript-3081/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.