Skip to content

Debouncing and Throttling in JavaScript or how to remove unnecessary API calls.

Debouncing and throttling in JavaScript is way to improve application performance. We can use debouncing or throttling to limit the amount of times the application runs function. 

Debouncing – run function after the action has finished for the defined amount of time. Candidate for this is autocomplete. You don’t want that your API is called after every letter is typed in autocomplete input field. Best would be to wait some amount of time after last letter is typed and then run function which call API.

Example: if you type in search field: ‘javascr’ without debouncing there would be 7 API calls, using debounce only 1.

const debounce = (cb, delay) => {
  let timeout
  return (...args) => {                 // return the throttled function
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      timeout = null
      cb(...args)                       // Run throttled function
    }, delay)
  }
}

// debounced function
function apiCall(){
    // do some expensive stuff
}

// On keyup, allow function to run 500ms after lest keyup
targetedEvent.addEventListener("keyup", debounce(apiCall, 500));

Throttle – run function while the action is being performed for the defined iteration time. Candidate for this is window resize or scrolling. If you add event listener to window scroll event which executes some function, executing function every time when event is fired is not the best solution. If API is called it could be very expensive. Much better solution is to execute that function every 300ms while scrolling a window, so instead of having 100 API calls we have 1-3 calls.

Here is how simple throttle function could look:


const throttle (cb, limit) => {
    var wait = false;                  // Initially, we're not waiting
    return () => {                     // return the throttled function
        if (!wait) {                   
            cb.call();                 // Run throttled function
            wait = true;               // Prevent invoking
            setTimeout(() => {   
                wait = false;          // Allow invoking
            }, limit);
        }
    }
}

// throttled function
function apiCall(){
    // do some expensive stuff
}

// On scroll, allow function to run at most 1 time per 300ms
window.addEventListener("scroll", throttle(apiCall, 300));

I recommend using lodash or underscore version of this functions or if you decide to create your own, test it in different browsers and devices.

Published injavascript performance

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *