Tutorials / Modern JavaScript: Async, Modules and the Browser / Performance basics: debounce and throttle

Performance basics: debounce and throttle

14 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

When events fire too often

Some events fire dozens of times per second. input fires on every keystroke, scroll and mousemove fire continuously, and resize fires over and over while you drag the window edge. If each event triggers something costly, such as an API call or a layout calculation, the page becomes slow, and the server gets hammered.

Two small techniques fix this: debounce and throttle. Both limit how often a function runs. They behave differently, and choosing the right one matters.

Debounce: wait until the user stops

A debounced function waits for a pause. Every new call restarts the timer. The function runs only when no new call has arrived for a given delay.

The classic use is a search box. You do not want to hit the server for "j", then "ja", then "jav", then "java". You want one request after the user stops typing.

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

const search = debounce(term => {
  console.log("Searching for:", term);
}, 300);

// simulate fast typing
search("j");
search("ja");
search("jav");
search("java");
// only "Searching for: java" is printed, about 300 ms later

How does it work? timer lives in the closure, so it is shared between calls. Each call cancels the pending timer with clearTimeout and starts a new one. Only the last call's timer is allowed to finish. Notice that this is the closure idea from the fundamentals course doing real work.

In the browser:

const input = document.querySelector("#search");
input.addEventListener("input", debounce(event => {
  loadResults(event.target.value);
}, 300));

A delay between 200 and 400 ms feels responsive but cuts most of the calls.

Throttle: at most once per interval

A throttled function runs at most once in every time window, however many calls come in. It is for continuous events where you want regular updates, not just the last one. Examples are updating a scroll position indicator, tracking mouse movement, or checking whether to load more items on infinite scroll.

function throttle(fn, interval) {
  let lastRun = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn.apply(this, args);
    }
  };
}

const logScroll = throttle(position => {
  console.log("Scroll position:", position);
}, 200);

// simulate 1000 quick events over about one second
let position = 0;
const timer = setInterval(() => {
  position += 10;
  logScroll(position);
  if (position >= 1000) clearInterval(timer);
}, 1);

On each call, we compare the current time with the last time we ran. If enough time has passed, we run the function and remember the time. Calls in between are ignored. So during a scroll lasting one second, the handler runs about five times and not a hundred.

Which one to use

SituationChoose
Search as you typeDebounce
Auto-save a draft after the user pausesDebounce
Validate a form field after typingDebounce
Scroll position, parallax, infinite scrollThrottle
Mouse move or dragThrottle
Window resize that needs live updatesThrottle
Window resize where only the final size mattersDebounce

A simple way to remember it: debounce means "wait until it calms down", and throttle means "no more than N times per second".

Cancelling a debounce

For cleanup, such as when a component is removed, it helps to be able to cancel a pending call:

function debounce(fn, delay) {
  let timer;
  function debounced(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  }
  debounced.cancel = () => clearTimeout(timer);
  return debounced;
}

Other cheap performance wins

Debounce and throttle are about calling less often. A few other habits give you much of the benefit:

  • Passive listeners. addEventListener("scroll", handler, { passive: true }) tells the browser your handler will not cancel scrolling, so it can scroll smoothly.
  • **requestAnimationFrame.** For visual updates, do the work inside requestAnimationFrame(callback). The browser calls it once before each repaint.
  • Batch DOM writes. Build elements first, then add them once. Use append with several nodes, or a DocumentFragment.
  • Avoid layout thrashing. Reading offsetHeight right after changing a style forces the browser to recalculate layout. Do your reads together, then your writes.
  • Cache selectors. Do not call querySelector inside a loop that runs 1000 times.
  • Measure first. Use the DevTools Performance tab before optimising. I have wasted time speeding up code that was never slow.

Libraries

Libraries such as Lodash provide debounce and throttle with options like leading and trailing edge. If you already use one, take theirs. For a small project, the ten lines above are enough, and you understand them.

Common mistakes

  • Creating the debounced function inside the handler. Each event makes a new function and a new timer, so nothing is debounced. Create it once, outside.
  • **Using an arrow function for the returned wrapper and then needing this.** The returned function in our helpers uses function so it can pass this through.
  • Picking too long a delay. A 2 second debounce on a search box feels broken.
  • Using throttle for search. You will send requests for half-typed words and the last, most important, keystroke may be skipped.
  • Forgetting to clear timers when a page or component goes away.

Try it yourself

  1. Add a debounced input listener to a text field that shows the character count 500 ms after you stop typing.
  2. Throttle a scroll listener to run every 250 ms, and display window.scrollY on the page.
  3. Add a cancel method to your throttle and write a test that calls it.
  4. Log how many times a plain handler and a throttled handler run during a 2 second mouse drag.
javascript
function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

const search = debounce(term => {
  console.log("Searching for:", term);
}, 300);

// simulate fast typing
search("j");
search("ja");
search("jav");
search("java");
// only "Searching for: java" is printed, about 300 ms later

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account