Rendering Optimization

Reduce page jank with debouncing, throttling, virtual lists, and techniques for long lists and high-frequency events.

🎯 Introduction

The previous article addressed slow page loading, but fast loading does not guarantee smooth interaction. A search field might send a request on every keystroke, a large list might freeze the page, or animations might stutter while scrolling. These are performance problems in the rendering stage.

By the end of this article, you will be able to:

  • Implement debouncing and throttling, explain their differences, and choose the right one.
  • Explain why long lists become slow and how virtual lists work.
  • Explain reflow and repaint, compare their costs, and reduce them by batching changes and separating reads from writes.

These techniques rely on JavaScript and browser behavior rather than a particular framework, so you can use them in any project.


🧱 Debouncing: Wait Until the Activity Stops

Consider search suggestions. As users type, you request suggestions for their input. If you handle every input event directly, typing “vue3” sends four requests. Users never look at the first three results, so those requests are wasted.

The solution is debouncing: wait before executing after an event. If another event occurs during that delay, restart the timer. Execute only after the activity settles.

Think of an elevator waiting for passengers. A countdown starts when the doors open. Each arriving passenger restarts it. The doors close only after nobody enters for a while, rather than making a separate trip for each passenger.

Implementation requires just one timer:

debounce.js
function debounce(fn, delay) {
    let timer = null; // Keep the previous timer in a closure

    return function (...args) {
        // Clear the old timer on every call to restart the countdown
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
}

Wrap the original handler to use it:

// Search suggestions: send a request only after typing stops for 300ms
const onInput = debounce((keyword) => {
    console.log('Sending search request:', keyword);
}, 300);

No request is sent while the user keeps typing. Requests happen only after a pause, changing their frequency from once per keystroke to once per pause.

Debouncing suits cases where only the final result matters: search suggestions, recalculating layout after window resizing, and autosaving form drafts.

🧱 Throttling: Execute at a Controlled Rate

Now consider handling scroll events to decide whether to show a “Back to top” button. A single drag of the scrollbar can trigger dozens of scroll events. Running a handler for every one is wasteful.

Debouncing is unsuitable here: the user might keep scrolling, and we want periodic updates during scrolling rather than waiting for it to stop. Throttling solves this: regardless of event frequency, execute at a fixed minimum interval and ignore calls within that interval.

Throttling is like a game ability's cooldown. Once activated, the ability cannot be used again until its cooldown ends, no matter how often you press the key. Rapid input does not increase its activation rate.

throttle.js
function throttle(fn, interval) {
    let lastTime = 0; // Time of the previous execution

    return function (...args) {
        const now = Date.now();
        // Ignore calls made before the interval has elapsed
        if (now - lastTime >= interval) {
            lastTime = now;
            fn.apply(this, args);
        }
    };
}

Again, wrap the handler:

// Scroll handler: execute at most once every 200ms
const onScroll = throttle(() => {
    console.log('Current scroll position:', window.scrollY);
}, 200);

window.addEventListener('scroll', onScroll);

Events still fire frequently, but the handler runs at most once every 200ms, immediately reducing overhead.


⚡ Debouncing vs. Throttling

These concepts are easy to confuse. This table compares them:

ComparisonDebouncingThrottling
Execution timingOnce after events stopAt fixed minimum intervals, even while events continue
Everyday analogyAn elevator waiting for passengersAn ability waiting for its cooldown
For n eventsUsually one execution, for the final eventRoughly n multiplied by the ratio of event spacing to throttle interval
Typical usesSearch suggestions, resize handling, autosaveScroll handling, pointer movement, preventing rapid repeated clicks

Remember: debouncing waits until you finish; throttling sets the pace. Ask whether you need the final result or ongoing feedback during the activity. Use debouncing for the former and throttling for the latter.

Both functions return a new function. Use that same returned function when adding and removing an event listener. For example, removeEventListener during Vue component unmounting must receive the wrapper originally registered.

🧱 Virtual Lists: Render Only What Is Visible

Suppose a page displays 10,000 records. Rendering all of them with v-for creates 10,000 DOM nodes at once. DOM nodes are expensive: creation, layout, and painting all consume resources. Too many nodes make both initial rendering and scrolling slow.

The key observation is that users see only a dozen or so rows at once. Rendering thousands of invisible rows wastes work. A virtual list renders only items near the viewport and updates them as the user scrolls, keeping the DOM node count down to a few dozen.

Think of an airport flight information display. Hundreds of flights may depart in a day, but the screen shows only a few rows at once. As you browse, the number of rows stays constant while their contents change. Virtual list DOM nodes act like those rows: reuse positions and replace content.

The mechanism has three steps:

  1. Preserve the total height: use a spacer with height equal to the item count multiplied by each item's height, so the scrollbar behaves as though all 10,000 rows were present.
  2. Calculate the visible range: listen for scrolling, divide scrollTop by the item height to find the starting index, and add the number of rows that fit in the viewport to determine the small slice to render.
  3. Position the slice: vertically offset an inner container with transform: translateY so the rendered items appear in the correct viewport position.

Here is a simplified illustration:

virtual-list.js
const itemHeight = 50; // Each item has a fixed height of 50px
const total = 10000; // 10,000 items in total
const visibleCount = 10; // About 10 items fit in the viewport

function getVisibleItems(scrollTop) {
    // 1. Find the first visible item
    const start = Math.floor(scrollTop / itemHeight);
    // 2. Extract the small slice to render: only 10 items
    // listData contains all 10,000 records
    const items = listData.slice(start, start + visibleCount);
    // 3. Offset the inner container to position the content correctly
    const offsetY = start * itemHeight;
    return { items, offsetY };
}

Whether total is 10,000 or 100,000, only visibleCount items are rendered. Scrolling updates just this small data slice and its offset, which is why virtual lists stay smooth.

This simplified version requires fixed item heights. Variable-height items, such as comments of different lengths, make the calculations considerably more complex. Prefer an existing library for that case.

In practice, you do not need to build this yourself. Vue 3 projects can use a mature library such as vue-virtual-scroller (locally tested with Node.js v22 and vue-virtual-scroller@2.0.0-beta.8):

pnpm add vue-virtual-scroller@2.0.0-beta.8
UserList.vue
<script setup>
import { RecycleScroller } from 'vue-virtual-scroller';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css';

// users contains 10,000 user records
defineProps(['users']);
</script>

<template>
    <RecycleScroller :items="users" :item-size="50" style="height: 500px">
        <template #default="{ item }">
            <div class="row">{{ item.name }}</div>
        </template>
    </RecycleScroller>
</template>

Specify the item height and container height, and the library handles the calculations. You only need to decide how each record is displayed.


🧱 Reflow and Repaint: How the Browser Draws a Page

Our final topic concerns the browser itself. Understanding why certain operations are expensive starts with two concepts: reflow and repaint.

At a high level, the browser first calculates each element's geometry—its dimensions and position—and then paints its colors, backgrounds, and text. Reflow and repaint correspond to these stages:

  • Reflow: geometry changes, such as dimensions, position, or font size, require recalculating layout. This can affect neighboring elements or even the whole tree. It resembles widening a parking space and having to redraw the lines for all the spaces after it.
  • Repaint: appearance changes, such as text or background color, require drawing again without recalculating geometry. It resembles repainting a parked car while leaving the parking-space markings untouched.

Reflow is generally much more expensive than repaint, because it includes layout calculation and is usually followed by painting. Common triggers include changing dimensions or positions, adding or removing DOM nodes, resizing the window, and reading certain layout properties, as explained below.


🛠 Three Ways to Reduce Reflows and Repaints

Since reflow is expensive, aim to reduce its frequency and scope. These three techniques are useful in everyday development.

Technique 1: Batch style changes instead of applying them individually.

Individual style changes can each trigger reflow. Switching a class applies the changes together, giving the browser one change to process:

// Avoid: three changes may cause three reflows
el.style.width = '100px';
el.style.height = '100px';
el.style.backgroundColor = 'skyblue';

// Prefer: define a class in advance and apply it once
el.classList.add('active');

Technique 2: Animate transform and opacity rather than top or left.

Changing top or left changes layout position and can trigger reflow every frame. The browser's compositor can handle transform operations—translation, scaling, and rotation—and opacity without reflow, allowing much smoother animation:

/* Avoid: changing layout on every frame */
.box {
    transition: left 0.3s;
}
.box.moved {
    left: 100px;
}

/* Prefer: move with transform without triggering reflow */
.box {
    transition: transform 0.3s;
}
.box.moved {
    transform: translateX(100px);
}

Technique 3: Separate reads from writes instead of interleaving them.

This is an easy trap to miss. Browsers do not necessarily reflow immediately after every style change. They collect consecutive changes and process them together, potentially handling ten changes in one reflow. But reading layout information between changes, through properties such as offsetTop, clientWidth, or getBoundingClientRect(), forces the browser to apply pending changes immediately to return an accurate value. That interrupts its batching optimization:

// Avoid: interleaved writes and reads force layout on every iteration
for (const el of items) {
    el.style.width = el.offsetTop + 10 + 'px';
}

// Prefer: batch all reads first, then all writes
const widths = items.map((el) => el.offsetTop + 10);
items.forEach((el, i) => {
    el.style.width = widths[i] + 'px';
});

Remember: read first, then write; keep them separate. Interleaving them in a loop hurts performance. Grouping reads before writes replaces repeated per-iteration reflows with batched work.


❓ Questions and Answers

Q1: If I can implement debouncing and throttling myself, do I still need lodash?

The implementations here cover common cases. Lodash's debounce and throttle offer additional options such as leading execution and maximum wait times. If the project already uses lodash, its utilities are convenient.

Q2: Should I debounce or throttle a button to prevent repeated clicks?

Throttle it, optionally with a longer cooldown. The goal is to accept only one click within a time window, which matches throttling. Debouncing waits until clicking stops before executing, which usually does not match the intended behavior.

Q3: Are virtual lists limited to fixed-height items?

Fixed-height items are simpler, but variable-height lists are possible. They require tracking and estimating individual heights, substantially increasing complexity. Use a library such as vue-virtual-scroller that already supports dynamic heights.

Q4: How can I check for frequent reflows?

Record an interaction in the Chrome DevTools Performance panel. Look for dense sequences of purple Layout events and green Paint events, and examine their durations.

Chrome DevTools changes between versions, so panel names and controls may differ. Treat these steps as guidance and follow your local interface; the underlying approach remains the same.

Q5: Should I try to eliminate all reflows and repaints?

No, and that is not possible. Changing page content naturally requires layout and painting. The goal is to avoid unnecessary, repeated, large-scale reflows, rather than eliminate them entirely.


🧪 Exercises

Exercise 1: Debounce the following search field so it logs the search term only after typing stops for 300ms. Copy the debounce implementation from this article.

SearchBox.vue
<script setup>
// Paste the debounce implementation here

function search(keyword) {
    console.log('Search:', keyword);
}

// Write your code here: wrap search with debounce using a 300ms delay
</script>

<template>
    <!-- Write your code here: bind the input event and call the wrapped function -->
    <input placeholder="Enter a search term" />
</template>

Exercise 2: The following code interleaves reads and writes in a loop over 500 items. Rewrite it to separate the two phases.

const items = document.querySelectorAll('.item');

// Write your code here: read all offsetTop values first, then write all height values
for (const el of items) {
    el.style.height = el.offsetTop + 20 + 'px';
}

🎉 You now have the tools to optimize rendering! You can address high-frequency events, long lists, and frequent reflows—three common causes of page jank. Next, we will explore HTTP caching to make resource loading more efficient.