Debouncing in JavaScript
Sending a Request Only after the User Has Stopped Typing
--
📚 Connect with us. Want to hear what’s new at The Pragmatic Bookshelf? Sign up for our newsletter. You’ll be the first to know about author speaking engagements, books in beta, new books in print, and promo codes that give you discounts of up to 40%.
The JavaScript language was invented to respond to user interactions on web pages. While most interactions are infrequent, some may happen repeatedly in a short period of time. If you code your program to execute a CPU-intensive function with each interaction, you might slow down the browser. You can’t simply remove the function because it’s a critical part of your program, but you also can’t let it undermine the performance of your program.
The solution is to implement a debounce function. Debouncing is a programming technique that enables you to ensure tasks do not fire so often. Take live search for example: an event fires at each key press, but if you immediately make a request with each event, you’ll unnecessarily bog down the server because the user might not have finished typing yet.
💡 If you are wondering what async is useful for, pick up Modern Asynchronous JavaScript (now in beta), which details all sorts of examples and patterns.
A better approach is to send a request only after the user has stopped typing for at least 200ms.
Debouncing Example
Let’s look at an example. We begin by creating an HTML input element to let the user type the search query:
<label for="searchInput">Search:</label>
<input type="search" id="searchInput">
Following is our JavaScript code. We define a debounce function to control the amount of time our main function runs. This way, the function won’t send out a fetch request immediately; instead, it delays the execution by 300 milliseconds:
// debounce function
function debounce(callback, limit) {
let timeout;
return () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
callback();
}, limit);
};
}// main function
async function queryGoogle(e){
// use your own API key in production
const api =…