DEV Community

Cover image for Comprehensive Guide to Debouncing in JavaScript: Improve Your Code Efficiency
Dipak Ahirav
Dipak Ahirav

Posted on • Edited on

Comprehensive Guide to Debouncing in JavaScript: Improve Your Code Efficiency

Learn how to implement debouncing in JavaScript with practical examples and tips. Master the debounce function and improve your web performance.

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

In this comprehensive guide, we will explore debouncing in JavaScript, understand its importance, and learn how to implement it effectively. Whether you are a beginner or an experienced developer, mastering debouncing can significantly improve your web performance.

Debouncing is a programming practice used to ensure that a time-consuming task does not fire so often, improving performance and user experience. It's particularly useful in scenarios like window resizing, button clicking, or form input events, where multiple rapid events need to be controlled.

What is Debouncing?

Debouncing is a technique to limit the rate at which a function is executed. When multiple events are triggered in quick succession, the debounce function will ensure that only the last event in the series triggers the function execution after a specified delay.

Why Use Debouncing?

  • Performance Optimization: Prevents performance issues by reducing the number of times a function is called.
  • Enhanced User Experience: Avoids the clutter of repeated actions, providing a smoother experience.
  • Network Efficiency: Reduces unnecessary network requests when used with event handlers like input fields for live search.

How Debouncing Works

Imagine a user typing in a search box that triggers an API call for each keystroke. Without debouncing, each keystroke would result in a new API call, flooding the network with requests. With debouncing, only the final input after the user stops typing for a specified duration will trigger the API call.

Implementing Debouncing in JavaScript

Here is a simple implementation of a debounce function:

function debounce(func, wait) {
    let timeout;

    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };

        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}
Enter fullscreen mode Exit fullscreen mode

Usage Example

Let's see how we can use the debounce function in a real-world scenario:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Debouncing Example</title>
</head>
<body>
    <input type="text" id="searchBox" placeholder="Type to search...">

    <script>
        const searchBox = document.getElementById('searchBox');

        function fetchSuggestions(query) {
            console.log('Fetching suggestions for:', query);
            // Simulate an API call
        }

        const debouncedFetchSuggestions = debounce(fetchSuggestions, 300);

        searchBox.addEventListener('input', (event) => {
            debouncedFetchSuggestions(event.target.value);
        });

        function debounce(func, wait) {
            let timeout;

            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };

                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example:

  • An input field captures the user's input.
  • The fetchSuggestions function is debounced with a delay of 300 milliseconds.
  • As the user types, the debouncedFetchSuggestions function is called, ensuring that fetchSuggestions is only executed once the user stops typing for 300 milliseconds.

Support My Work

If you enjoy my content and want to support my work, consider buying me a coffee! Your support helps me continue creating valuable content for the developer community.

Conclusion

Debouncing is a simple yet powerful technique to optimize the performance of web applications. By controlling the rate of function execution, it helps in reducing unnecessary computations and improving the overall user experience. Whether you're handling search inputs, resizing windows, or dealing with other rapid events, debouncing can be a valuable tool in your JavaScript arsenal.

Series Index

Part Title Link
1 Ditch Passwords: Add Facial Recognition to Your Website with FACEIO Read
2 The Ultimate Git Command Cheatsheet Read
3 Top 12 JavaScript Resources for Learning and Mastery Read
4 Angular vs. React: A Comprehensive Comparison Read
5 Top 10 JavaScript Best Practices for Writing Clean Code Read
6 Top 20 JavaScript Tricks and Tips for Every Developer 🚀 Read
7 8 Exciting New JavaScript Concepts You Need to Know Read
8 Top 7 Tips for Managing State in JavaScript Applications Read
9 🔒 Essential Node.js Security Best Practices Read
10 10 Best Practices for Optimizing Angular Performance Read
11 Top 10 React Performance Optimization Techniques Read
12 Top 15 JavaScript Projects to Boost Your Portfolio Read
13 6 Repositories To Master Node.js Read
14 Best 6 Repositories To Master Next.js Read
15 Top 5 JavaScript Libraries for Building Interactive UI Read
16 Top 3 JavaScript Concepts Every Developer Should Know Read
17 20 Ways to Improve Node.js Performance at Scale Read
18 Boost Your Node.js App Performance with Compression Middleware Read
19 Understanding Dijkstra's Algorithm: A Step-by-Step Guide Read
20 Understanding NPM and NVM: Essential Tools for Node.js Development Read

Follow me for more tutorials and tips on web development. Feel free to leave comments or questions below!

Follow and Subscribe:

Top comments (20)

Collapse
 
seanfrisbey profile image
Sean Frisbey

Having come from a hardware background, the way "denouncing" is used in software bother's me 🥲

Collapse
 
aliasfoxkde profile image
Micheal Kinney

Exactly the reason I read this article. I had to know what debouncing meant in software terms.. I thought it was long dead with CRT monitors. And maybe it's just my own ignorance, but I feel caching accomplishes the same with added benefits.

Collapse
 
armando284 profile image
Armando

Caching and debouncing are two different concepts that target different problems, with caching you could, for example, not calling the API since you already have the data saved on your client’s RAM; debouncing on the other hand would stop the call to the function that calls your API or cached data until sometime has passed. For example on a Google place input with autocomplete for places if you don’t use debouncing and the user wants to search for “new y” you’ll have several calls to your autocomplete API as the user writes since it’s attached to the input event: “n”, “ne”, “new”, “new “, and “new y” so you’ll get 5 calls to your API when the user only needs the last one, debouncing will make only the last event calls your API or if you want, your cached data.

Collapse
 
vivek1052 profile image
Vivek Parashar

Exactly. Undergrad myself still thinks debouncing as eliminating short button click due to contact noise

Collapse
 
nur_ammarnaufal_ef46fe3e profile image
Nur Ammar Naufal

lets code arduino wkwkwk

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited

Not reusable, but just in case you want to have debounce feature on your search box that appears just once forever:

let debounce;
node.addEventListener('keydown', function () {
    debounce && clearTimeout(debounce);
    debounce = setTimeout(() => {
        console.info('Yo!');
        console.info(this.value);
    }, 300);
}, false);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jeffrey_tackett_5ef1a0bdf profile image
Jeffrey Tackett

The biggest issue I have with debounce is the delay (aka, input lag), where users do notice that it isn't like a switch in the real world. There is even an interview with John Carmack, in which he complained that all UI components for computers are wrong because they wait for a full click instead of changing state on mouse button down. So, debounce adds an additional delay and that is my complaint with this simple implementation, I have made a version that would trigger the first event immediately and would consume any additional events until it would timeout. This is the inversion of the design given in this article, the cool thing about my design is that it can be used for notifications that self dismiss and then, using a queue, would display the next one.

Collapse
 
flyaku profile image
Flyaku

Full click allows users to maintain click and get out of a button without triggering it, it's handy.

Collapse
 
marcelomsc profile image
Marcelo

On the input from user, you can use an image of a search element to when user click do the search. Sometimes, we complicated things that don't need to be complicate...
I think that UI Designer are always making things that don't improve user experience, but looks good on the screen. kkkkkk

Collapse
 
jangelodev profile image
João Angelo

Top, very nice !
Thanks for sharing

Collapse
 
tojacob profile image
Jacob Samuel G.

Simple but powerful

Collapse
 
dipakahirav profile image
Dipak Ahirav • Edited

Thank you @tojacob ..please subscribe to my YouTube channel to support my channel and get more web development tutorials.

Collapse
 
alidarrudi profile image
ali

Simple, concise, useful

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you so much @alidarrudi for your kind words and feedback! 🙏 I'm thrilled to hear that you found the post helpful. Your support means a lot to me. If you enjoyed this post, please consider subscribing to my YouTube channel devDive with Dipak for more content. Don’t forget to share it with your friends and help spread the word. Your support helps me to continue creating valuable content. Thanks again! 😊

Collapse
 
buarki profile image
buarki

very straightforward and handy, bro! keep it up

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you so much @buarki for your kind words and feedback! 🙏 I'm thrilled to hear that you found the post helpful. Your support means a lot to me. If you enjoyed this post, please consider subscribing to my YouTube channel devDive with Dipak for more content. Don’t forget to share it with your friends and help spread the word. Your support helps me to continue creating valuable content. Thanks again! 😊

Collapse
 
pratiksha_ganage_9fb67d6d profile image
pratiksha ganage

Thank you so much. This helped me to clear my concept about debouncing.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you so much @pratiksha_ganage_9fb67d6d for your kind words and feedback! 🙏 I'm thrilled to hear that you found the post helpful. Your support means a lot to me. If you enjoyed this post, please consider subscribing to my YouTube channel devDive with Dipak for more content. Don’t forget to share it with your friends and help spread the word. Your support helps me to continue creating valuable content. Thanks again! 😊

Collapse
 
cascod profile image
56LeoMessi

Thanks for this article.
Simple yet effective.
Would definitely try sometime.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thank you @cascod .please subscribe to my YouTube channel to support my channel and get more web development tutorials.