Understanding Debouncing and Throttling in JavaScript

Optimizing your code is one of the most effective ways to improve your application’s performance. Debounce and throttling are two essential code optimization techniques for JavaScript. Using both techniques will help in improving your app’s user experience, and you’ll also save yourself quite a bit of money.

The Default Behavior of DOM Access

Before diving deep into debounce and throttling, you need to understand why both techniques are important using some example code.

Create anindex.htmlfile and paste the following code into it:

4

The first element is an input for collecting information. Then there are threedivsand an innerspanelement for outputting the text in default, debounce, and throttling modes. The purpose of these elements is to demonstrate and compare the three techniques with each other.

Create thescript.jsfile, and start by selecting all the page elements:

Man working in Macbook pro

For a deep dive into DOM access methods likequerySelector(), you need to understandDOM traversing in JavaScript.

Next,add an event listenerto the input. This just takes whatever is typed into the form and passes it as the inner content of the firstspanelement:

Screenshot of default text

When you type something into your input, the text displays on the page as shown in the following image.

This default method of printing values works when you’re just working locally on your computer. The process is super quick, and it’s not going to cause any performance problems no matter what your network connection is. This is because you’re just storing everything locally on your page. The problem arises when you’re getting data from an external server.

Screenshot of debounce text-1

The Problem in Making Multiple Function Calls

Imagine that the input is an autocomplete box. When you type something into the box, it goes to the server and queries a bunch of information. For example, you might be querying the database to retrieve all the moves that have the termmatrixin it.

Here’s the problem: as you type each character, the code sends a brand-new request because theinputevent gets fired every time you type in a new character.

Screenshot of true debounce

So when you typem, it’s going to make a request for all the movies that start withm. When you doma, it sends another request and returns the movies starting withma.And so on.

By typing the wordmatrix, we make six requests to our server. This is not only going to cause some UI problems, but it’s also a huge burden for those using your code. This is because they have to make six network requests, which is going to slow down the app if they’re on a slow connection.

This is where debouncing and throttling come into play. Both techniques help you conserve resources by making fewer requests. Instead of calling a function every single time, it only calls that function after a set delay. That delay is going to be different based on debouncing and throttling (both methods work differently).

Using the Debounce Technique

Rather than calling a function every time you type a character into an input field, the debounce works by calling the function and waiting a specified amount of time (e.g. one second).

If nothing changes in that time frame, then it invokes the function. But if during that one second, you type another character, it’ll notice the change and reset the timer back to the specified delay time (one second).

Essentially, debounce waits for a period of time (set by you), and if nothing changes during that time, it calls the function. But if there is a change, then the timer is reset. The debounce technique can be better understood with the help of some code.

Beneath the first event listener, create a function nameddebounce. You’ll pass a callback function to debounce, as well as a default delay of one second.

Basically, you’re forcing the function to wait for one second before running the callback function. Next, pass the debounce function toupdateDebounceText. Give it a callback function that takes a text as an argument and updates thedebounceTextelement with the text content.

The callback is an anonymous function, which is a special way to writefunctions in JavaScript. Finally, call theupdateDebounceTextfunction inside the event listener, so it accesses the input text and prints it on the page:

Save the file and go to your browser. As you type into the form input, you’d notice a one-second delay until the text appears next toDebounce.

This is not exactly how the debounce technique works. You’re just delaying things by a second here.

Instead, you want to make sure that all of those function calls for each character don’t run until you’re done typing everything. You do this by clearing a timeout anytime you call the function. Here’s the modified code for that:

So every time your input changes, you call theupdateDebounceTextfunction which clears your original timeout and starts a new one-second timer. As a result, the function waits until there’s at least a one-second delay before running the callback again.

The image below captures the page just after typing the last character in the form:

In this case, it updates all the input at once. This is because every time we typed a new character, the timer resets, which is why the character wasn’t added to the page.

Debouncing is really useful in these scenarios where you want to send information in after a given delay rather than on every update.

Understanding the Throttle Technique

Throttle is a bit different from the debounce technique. Similar to debouncing, throttling delays your function call. But instead of waiting until everything is done, it continually sends a new request with the latest batch of information.

So if your delay is four seconds, then the throttle function will send the first batch of characters, wait for four seconds, then send the new batch of characters that you typed in during the delay.

The throttling technique is useful when several things are changing, and you want to just send the most recent update. An example use-case would be when resizing a window or scrolling the window. You want to figure out the user’s location, but you don’t want to call the method a hundred thousand times.

The throttle technique will limit the amount of power that the CPU will need. Here’s the throttle function:

The first time you callthrottle(), it immediately calls your callback function. And then every other time you call it, it does nothing until your delay has finished. Once it has finished, you resetshouldWaittofalse(which runs the code and repeats the process).

Call the throttle function and pass in the callback:

Next, call the function in the event handler:

Now if you type into the input, the characters are updated in batches in one-second intervals. The following image captures the page just before outputting the second batch of characters (ix).

More About JavaScript Optimization

An optimized code is essential for boosting your application’s speed and overall performance. JavaScript is naturally a fast language, but poor coding practices can hinder the performance of your application. This is why you need to be familiar with the different optimization techniques for JavaScriot code if you want to be a top one percent developer.

Learn how to speed up your web pages by tweaking your JavaScript to remove bottlenecks.

You can block out the constant surveillance and restore your privacy with a few quick changes.

My foolproof plan is to use Windows 10 until 2030, with the latest security updates.

I found my TV was always listening—so I shut it down.

The key is not to spook your friends with over-the-top shenanigans.

These films will leave you questioning humanity, but also wanting more.

Technology Explained

PC & Mobile