Debouncing and Throttling in JavaScript

Debouncing and Throttling in JavaScript

This article would be taking about debouncing and Throttling to enhance the performance of webpages.

Debouncing and Throttling are the techniques used to limit the number of function calls.

###Debouncing

In the debouncing technique, no matter how many times the user fires the event, the attached function will be executed only after the specified time once the user stops firing the event.. lets write a small function to demonstrate debouncing in JavaScript

let callCount = 0;

// this is just a promise that resolves after 300ms
// and console logs a counter
function apiCall() {
  return new Promise(resolve => {
    setTimeout(() => {
      callCount++
      console.log("Calls Made:" + callCount)
      resolve()
    }, 300)
  })
}

fakeAPICall() // 1
fakeAPICall() // 2
fakeAPICall() // 3

function debounce (callback) {
let timeoutId;
return () => {
 clearTimeout(timeoutId)
   timeoutId = setTimeout(callback, 800)
  }
}

const debounceFakeApiCall = debounce(apiCall);
// all the calls below would be cancelling themself
// untill the last call where it timeout

debouncedFakeApiCall()
debouncedFakeApiCall()
debouncedFakeApiCall()
debouncedFakeApiCall()
debouncedFakeApiCall()
debouncedFakeApiCall()
debouncedFakeApiCall() // 4

How it Works ?

The most basic, critical piece of this debounce function is to delay the actual API call, then as more calls come in, cancel and reset the delay for the API call. We do this with setTimeout and clearTimeout in the JavaScript above.

what is a throttle ?

Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be executed only once in a given time interval.

let callCount = 0

function fakeAPICall() {
  return new Promise(resolve => {
    setTimeout(() => {
      callCount++
      console.log("Calls Made:" + callCount)
      resolve()
    }, 300)
  })
}

function throttle(cb) {
    let makingCall
    return function() {
      // if I'm in progress of making an API call,
      // don't trigger another one
      if (makingCall) return
      // set up API call to fire
      makingCall = true
      // give the user some time to type by delaying the actual call
      setTimeout(() => {
        makingCall = false
        cb()
      }, 800)
    }
}

const throttledFakeApiCall = throttle(fakeAPICall)

// imagine the user starting and stopping typing
// we'll only make a call every 800ms
throttledFakeApiCall() // 1
throttledFakeApiCall()
throttledFakeApiCall()
setTimeout(() => {
  throttledFakeApiCall()
  throttledFakeApiCall()
}, 600)
setTimeout(() => {
  throttledFakeApiCall() // 2
  throttledFakeApiCall()
}, 1200)
setTimeout(() => {
  throttledFakeApiCall()
  throttledFakeApiCall()
}, 1800)
setTimeout(() => {
  throttledFakeApiCall() // 3
  throttledFakeApiCall()
}, 2400)

Now as our throttle function fires, we are limiting our calls to happen every 800ms.