# Performance & Rendering

> Understand the browser's render pipeline. Learn how to avoid Layout Thrashing and keep your application running at a buttery-smooth 60 frames per second.

Subject: JavaScript | Lesson 59 of 63 | 8 min read
Interactive lesson: https://codewithanimation.in/javascript/performance-and-rendering
Previous: [Immutability & Pure Functions](https://codewithanimation.in/javascript/immutability-and-pure-functions.md) | Next: [Debugging & the Console](https://codewithanimation.in/javascript/debugging-and-console.md)

## The 16.6ms Deadline

To achieve a smooth 60 frames per second (fps), the browser must complete all JavaScript execution, style calculations, layout geometry, and painting within 16.6 milliseconds.

If your JavaScript takes 30ms to execute, the browser misses a frame. This is called 'jank'.

## The Cost of Layout Thrashing

When you change the DOM (like altering a width or adding a class), the browser invalidates the layout. If you immediately ask the browser for a geometric property (like `element.offsetHeight`), the browser is forced to pause JavaScript and synchronously recalculate the entire page layout right then and there.

If you do this in a `for` loop, you trigger **Layout Thrashing**-forcing the browser to recalculate the layout dozens of times in a single frame, destroying performance.

## Batching Reads and Writes

The fix is simple: separate your Reads from your Writes.

**Bad (Thrashing):**

```javascript
for (let i = 0; i < items.length; i++) {
  const h = items[i].offsetHeight; // Read
  items[i].style.height = (h + 10) + 'px'; // Write (Invalidates layout!)
}
```

**Good (Batched):**

```javascript
// Read everything first
const heights = items.map(item => item.offsetHeight);

// Then write everything
items.forEach((item, i) => {
  item.style.height = (heights[i] + 10) + 'px';
});
```

## Common mistake: Hidden Layout Triggers

It is not just `offsetHeight` that triggers synchronous layout calculations. Properties like `clientWidth`, `scrollTop`, `getBoundingClientRect()`, and even calling `getComputedStyle()` will force a layout if the DOM has pending mutations.

Always be paranoid about when you read geometry from the DOM.

## Tip: requestAnimationFrame

If you are animating something directly with JavaScript, never use `setTimeout` or `setInterval`. Use `requestAnimationFrame()`. It tells the browser that you wish to perform an animation and requests that the browser call your function right before the *next* repaint, syncing perfectly with the display's refresh rate.

## Try it: The 16.6ms Timeline

Examine the performance profiles below. Notice how mixing Reads and Writes forces the browser into a vicious cycle of expensive layout recalculations, missing the frame deadline. Batching solves this instantly.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/performance-and-rendering

## Check yourself

### Question 1

What is 'Layout Thrashing'?

- A. Interleaving DOM reads and DOM writes in rapid succession, forcing the browser to recalculate layout multiple times per frame.
- B. Putting too many elements on a single HTML page.
- C. Using CSS Grid and Flexbox on the same element.

Correct answer: A

Thrashing occurs when you write to the DOM (invalidating the current layout) and then immediately ask for a geometric measurement (forcing a synchronous recalculation) over and over again.

- Why not B: Incorrect. While a large DOM tree is slow, 'thrashing' specifically refers to the sync read/write cycle.
- Why not C: Incorrect. You can safely combine Grid and Flexbox.

### Question 2

Why should you use `requestAnimationFrame` instead of `setTimeout` for animations?

- A. Because `requestAnimationFrame` is perfectly synchronized with the browser's native repaint cycle, eliminating screen tearing and jank.
- B. Because `setTimeout` runs on the GPU.
- C. Because `requestAnimationFrame` automatically uses WebGL.

Correct answer: A

`requestAnimationFrame` fires precisely when the browser is ready to paint the next frame (typically 60 times a second), ensuring maximum smoothness and battery efficiency.

- Why not B: Incorrect. `setTimeout` runs on the CPU's main thread.
- Why not C: Incorrect. It just schedules a function call; it doesn't change the rendering technology.

### Question 3

Which of the following will force a synchronous layout recalculation if the DOM has been mutated?

- A. Calling `element.getBoundingClientRect()`
- B. Calling `element.addEventListener()`
- C. Calling `console.log(element)`

Correct answer: A

`getBoundingClientRect()` requires the browser to know exactly where the element is on the screen right now. If there are pending DOM changes, it must pause and calculate the layout first.

- Why not B: Incorrect. Adding a listener doesn't require geometric measurements.
- Why not C: Incorrect. Logging a reference doesn't calculate geometry.

## Remember this

- The browser strives for 60 frames per second. You have **16.6ms** to complete all JavaScript and rendering work per frame.
- If you exceed 16.6ms, the browser drops a frame, resulting in noticeable 'jank'.
- **Layout Thrashing** happens when you interleave DOM reads (like `offsetHeight`) and DOM writes (like `style.height`).
- Prevent thrashing by **batching**: do all your DOM reads first, save the values, and then do all your DOM writes.
- Always use `requestAnimationFrame` for JavaScript-driven animations instead of `setTimeout`.
