Debounce and throttle explained with WordPress search and scroll examples

Debounce and throttle with WordPress search and scroll examples

Debounce and throttle limit how often a function runs in response to fast, repeated events: keystrokes, scrolling, window resizing. Without them, a live search sends a request on every key press, and a scroll handler runs dozens of times per second and makes the page stutter.

  • Debounce waits until the events stop: the function runs once, a set time after the last event. Each new event restarts the timer. Right for inputs, where you want to act when the user stops typing.
  • Throttle runs the function at most once per interval while the events continue. Right for scroll and resize, where updates should come at a steady rate.

Problem: A live search sends a REST request on every keystroke, and a scroll handler fires hundreds of times per second, causing extra network traffic and jank.

Solution: Wrap the search handler in debounce and the scroll handler in throttle. Both are a few lines of plain JavaScript, no Lodash needed.

The two helpers

// Run fn only after `wait` ms without new calls
function debounce( fn, wait ) {
    let timer;
    return function ( ...args ) {
        clearTimeout( timer );
        timer = setTimeout( () => fn.apply( this, args ), wait );
    };
}

// Run fn at most once every `limit` ms
function throttle( fn, limit ) {
    let lastRun = 0;
    return function ( ...args ) {
        const now = Date.now();
        if ( now - lastRun >= limit ) {
            lastRun = now;
            fn.apply( this, args );
        }
    };
}

This throttle runs on the first event of each interval and skips the rest, so the very last scroll position may be missed. For a sticky header that does not matter; if it does, add a trailing call with setTimeout or use Lodash’s _.throttle, which has both.

Live search with debounce

The REST settings (haRest.root) are passed from PHP as in calling the REST API with fetch().

const searchInput = document.querySelector( '#live-search' );
const resultsList = document.querySelector( '#search-results' );
let lastQuery = '';

const handleSearch = debounce( async function ( e ) {
    const query = e.target.value.trim();
    lastQuery = query;

    if ( query.length < 2 ) {
        resultsList.innerHTML = '';
        return;
    }

    const response = await fetch( haRest.root + 'wp/v2/posts?search=' + encodeURIComponent( query ) + '&per_page=5&_fields=title,link' );
    const posts = response.ok ? await response.json() : [];

    if ( query !== lastQuery ) {
        return; // the user typed more while this request was running
    }

    resultsList.innerHTML = '';
    posts.forEach( ( post ) => {
        const li = document.createElement( 'li' );
        const a = document.createElement( 'a' );
        a.href = post.link;
        a.innerHTML = post.title.rendered;
        li.appendChild( a );
        resultsList.appendChild( li );
    } );
}, 400 );

if ( searchInput && resultsList ) {
    searchInput.addEventListener( 'input', handleSearch );
}

Debounce reduces the number of requests, but a slow response can still arrive after a newer one; the lastQuery check drops such stale results. The minimum of 2 characters avoids requests for single letters.

Sticky header with throttle

const header = document.querySelector( '.site-header' );

const handleScroll = throttle( function () {
    header.classList.toggle( 'is-sticky', window.scrollY > 80 );
}, 100 );

if ( header ) {
    window.addEventListener( 'scroll', handleScroll, { passive: true } );
}

{ passive: true } tells the browser that the handler never calls preventDefault(), so it can scroll without waiting for it.

Resize with debounce

Expensive recalculations (a masonry grid, a slider) are better done once, after the user has finished resizing:

window.addEventListener( 'resize', debounce( function () {
    // your own layout function, for example recalculating the grid
    document.querySelectorAll( '.masonry-grid' ).forEach( ( grid ) => grid.dispatchEvent( new Event( 'relayout' ) ) );
}, 250 ) );

NOTE: To react to an element entering the viewport (animations, lazy loading), you do not need a throttled scroll handler at all: the Intersection Observer API does it without listening to scroll.