Debouncing and throttling techniques are used to limit the number of times a function can execute. Generally, how many times or when a function will be executed is decided by the developer. But in some cases, developers give this ability to the users. Now, it is up to the user to decide when and how many times to execute that function.

For instance, functions attached to events like button click, mouse move, and window resize allow the user to decide when to execute them and how many times to do so. At times, users may perform these actions more frequently than it is required. This may not be good for the performance of the website, especially if the functions attached to these events perform some heavy computation. In such cases, where users have control over function execution, developers have to design some techniques to restrict the number of times users can execute the function.

Let’s consider an example of a search bar on a website. Every time you type something in the search bar, it makes an API call to fetch the data from the server on the basis of the letters typed in the search bar.

Let’s have a look at the code. For simplicity, we have not passed the parameter (that is, the word typed by the user in the search bar) to the makeAPICall function.

issueWithoutDebounceThrottling.js
var searchBoxDom = document.getElementById('search-box');

function makeAPICall() {
// This represents a very heavy metho which takes a lot of time to execute
}

// Add "input" event listener on the text box or search bar
searchBoxDom.addEventListener('input', function () {
var showApiCallCountDom = document.getElementById('show-api-call-count');
var apiCallCount = showApiCallCountDom.innerHTML || 0;

// A very heavy method which takes a lot of time to execute
makeAPICall()

apiCallCount = parseInt(apiCallCount) + 1;
// Updates the number of times makeAPICall method is called
showApiCallCountDom.innerHTML = apiCallCount;
})
The above code renders an HTML page with a textbox. On the textbox, we have added an oninput event listener that calls an anonymous function. The anonymous function is called each time the user types in the textbox.

The anonymous function displays the number of times the oninput event has been fired by the user while typing. Inside the anonymous function, we are calling the makeAPICall function, which performs some heavy computation. The makeAPICall function calls an API that fetches data from the database and does some processing on that data and then returns the response.

Suppose the makeAPICall function takes 500 milliseconds to get data from the API. Now, if the user can type 1 letter per 100 milliseconds, then the makeAPICall function will be called 5 times in 500 milliseconds. Thus even before the makeAPICall has completed its task and returned the response, we are making 4 more API calls, which will put extra load on the server.

Moreover, these API calls are redundant! We could have fetched the desired data in just one API call after the user had completed typing. But, how can we decide if the user has stopped typing? In such a case, we could have assumed that if the user doesn’t type for 200 milliseconds then he is done with typing. We will call the makeAPICall function only if the user doesn’t type for 200 milliseconds. So basically, in this case, we have limited the number of times our makeAPICall function was called.

This technique of limiting the number of times the user can call a function attached to an event listener is debouncing and throttling. Debouncing and throttling also prevents the server from being bombarded by the API calls.

Let’s try to understand both these concepts with the help of a real-life example:

Throttling

Imagine yourself as a 7-year-old toddler who loves to eat chocolate cake! Today your mom has made one, but it's not for you, it's for the guests! You, being spunky, keep on asking her for the cake. Finally, she gives you the cake. But, you keep on asking her for more. Annoyed, she agrees to give you more cake with a condition that you can have the cake only after an hour. Still, you keep on asking her for the cake, but now she ignores you. Finally, after an interval of one hour, you get more cake. If you ask for more, you will get it only after an hour, no matter how many times you ask her.

This is what throttling is!

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.

For instance, when a user clicks on a button, a helloWorld function is executed which prints Hello, world on the console. Now, when throttling is applied with 1000 milliseconds to this helloWorld function, no matter how many times the user clicks on the button, Hello, world will be printed only once in 1000 milliseconds. Throttling ensures that the function executes at a regular interval.

Implementing Throttling in JavaScript
Throttling will change the function in such a way that it can be fired at most once in a time interval. For instance, throttling will execute the function only one time in 1000 milliseconds, no matter how many times the user clicks the button.

the above image, we can see that when the user is scrolling, the number of scroll event is much larger than the number of times throttling executed the function. Also, throttling executed the function at regular intervals, irrespective of the number of time scroll event is fired. Let’s check the code for the throttling.

throttling.js

var timerId;
var divBodyDom = document.getElementById('div-body');

// This represents a very heavy method which takes a lot of time to execute
function makeAPICall() {
var debounceDom = document.getElementById('debounc-count');
var debounceCount = debounceDom.innerHTML || 0;

debounceDom.innerHTML = parseInt(debounceCount) + 1
}

// Throttle function: Input as function which needs to be throttled and delay is the time interval in milliseconds
var throttleFunction = function (func, delay) {
// If setTimeout is already scheduled, no need to do anything
if (timerId) {
return
}

// Schedule a setTimeout after delay seconds
timerId = setTimeout(function () {
func()

// Once setTimeout function execution is finished, timerId = undefined so that in <br>
// the next scroll event function execution can be scheduled by the setTimeout
timerId = undefined;
}, delay)
}

// Event listener on the input box
divBodyDom.addEventListener/ Event listener on the input box
divBodyDom.addEventListener('scroll', function () {
var apiCallCountDom = document.getElementById('show-api-call-count');
var apiCallCount = apiCallCountDom.innerHTML || 0;
apiCallCount = parseInt(apiCallCount) + 1;

// Updates the number of times makeAPICall method is called
apiCallCountDom.innerHTML = apiCallCount;

// Throttles makeAPICall method such that it is called once in every 200 milliseconds
throttleFunction(makeAPICall, 200)
})
The above code renders a div with a scrollbar. We have added an event listener on the scroll event. Each time the user scrolls, an anonymous function is called that prints the number of times the scroll event is fired. When the user scrolls, we want to execute the makeAPICall method. But, as this method is heavy, attaching it to a scroll event directly will cause it to fire frequently. This may cause unnecessary load on the server. To prevent this, we have used the technique of throttling.

Let's examine the above code line by line:

When the first scroll event is fired, throttleFunction is called with the makeAPICall function and delay in milliseconds as parameters.
Inside throttleFunction, timerId is undefined, as it has not been initialized yet. So, we will go ahead and schedule the func that is themakeAPICall function using the setTimeout function. The setTimeout function will execute the func or the makeAPICall function after 200 milliseconds. Now, timerId will have the unique id of this setTimeout function.
When the second event for the scroll is fired, timerId is not undefined inside throttleFunction, so the function will return without scheduling the execution of makeAPICall. If timerId is not undefined it means that a setTimeout function has already been scheduled, hence we do not need to schedule another function.
Thus, unless and until setTimeout executes the makeAPICall function, we will not be able to schedule another makeAPICall function using setTimeout. This ensures that the makeAPICall function will be called only once in an interval.
The point to be noted is: inside the setTimeout function we have changed timerId to undefined, so once the scheduled makeAPICall function has been executed and the user again performs the scroll, throttleFunction will schedule the execution of the makeAPICall function with the help of the setTimeout function. Thus the makeAPICall function will be executed only once in a given interval.

Use of Debouncing and Throttling in Real Life
We can throttle a button click event, if we do not want the user to spam by clicking the button frequently.
In the case of window resize event, if we want to redraw the UI only when the user has fixed the size of the window, we can use debouncing.
With Mouse move event, if we are displaying the location coordinates of the mouse pointer, it is much better to show the coordinates once the user reached the desired location. Here, we can use debouncing.

Conclusion
In this article, we understood the concepts of debouncing and throttling along with their uses in the real world. We also implemented both the concepts using HTML and JavaScript.

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

下载和观看 鬼灭之刃剧场版:无限列车篇 2020 (Demon Slayer: Kimetsu no Yaiba) 完整版本 HD/BluRay

Up & Running with React Native + Visual Studio Mobile Center

Getting Started With Testing in JS

Introducing the Angular Dev Tools

Function declaration, expression, and arrow functions in Javascript.

How to Deploy an Angular App on Firebase And also Add GitHub Workflow.

Vue.js + GSAP = 🔥 Animations

React Native Authentication in Depth Part 2 — Real World Auth Flow

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aartisingh

Aartisingh

More from Medium

Alex Levin Enjoys Rave Reviews for The Modern Abstract Jerusalem and Jewish Paintings

Proles: Humans of Orwell’s Dystopia (Part 1)

Being a Girl In Today’s Society

Before you make that language learning New Year’s Resolution ….