Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Debounce Method
3.
Throttle Method
4.
Difference between Debounce and Throttle
5.
Use of Debouncing and Throttling in Real Life
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Debounce and Throttle

Introduction 

Limiting how often the function is run is recommended when adding a performant-heavy function to an event listener in JavaScript.

Debouncing and throttling approaches limit the number of times a function can execute. In most cases, the developer decides how many times or when a function will be performed. However, in some circumstances, developers provide consumers with this ability. It is now up to the user to select when and how often that function should be executed.

So, we will see such functions as debounce() and throttle() in this blog.

For example-

Html file 

<html>
    <body>
        <h2>Coding Ninjas</h2>
        <label>Search</label>
        <!-- Renders an HTML input box -->
        <input  type="text" id="search-box" />
        
        <p>No of times event fired</p>
        <p id='show-api-call-count'></p>
    </body>
    
    <script src="issueWithoutDebounceThrottling.js"></script>
</html>


JS file

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;
})
You can also try this code with Online Javascript Compiler
Run Code

 

Output- 

Debounce Method

The debouncing method restricts the time-consuming tasks or functions from firing often. By doing so, it enhances the efficiency of the system. JavaScript provides the debounce() function to achieve debouncing. The debounce() function in JavaScript restricts a function from running again for a certain period of time. The number of times a function can be called is limited due to this.

The debounce() function reduces the program's overhead by preventing the function from being called multiple times.

Let's go through an example to understand debouncing in JavaScript.

<html>
   <body>
      <button id="debounce">
      Button
      </button>
      
      <script>
         var button = document.getElementById("debounce");
         const debounce = (func, delay) => {
         let debounceTimer
         return function() {
         const context = this
         const args = arguments
         clearTimeout(debounceTimer)
         debounceTimer
         = setTimeout(() => func.apply(context, args), delay)
         }
         }
         button.addEventListener('click', debounce(function() {
         alert("Hello, regardless of how many times you click the debounce button, I'm performed once every 3 seconds!!")
         }, 3000));
      </script>
   </body>
</html>

 

Output-

Throttle Method

Throttling can be achieved using the throttle() function used in websites. We use throttling to call a function after every millisecond or a particular time interval.

For example, when the throttle function is absent on our website, which contains a button and if that button is pressed many times, the function will be executed the exact number of times.

But suppose the website contains a throttle() function. In that case, every click will be executed after a pre-defined interval of time except the first time the button is pressed, which will be executed immediately after the button is pressed.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport"
         content="width=device-width, initial-scale=1.0">
      <title>
         JavaScript with Throttling
      </title>
   </head>
   
   <body>
      <button id="throttle">Button</button>
      <script>
         const btn=document.querySelector("#throttle");
         
         const throttleFunction=(func, delay)=>{
         
         
         let prev = 0;
         return (...args) => {
         let now = new Date().getTime();
         
         
         console.log(now-prev, delay);
         
         if(now - prev> delay){
         prev = now;
         
         
         return func(...args);
         }
         }
         }
         btn.addEventListener("click", throttleFunction(()=>{
         console.log("button is clicked")
         }, 1500));
      </script>
   </body>
</html>

 

Output-

Difference between Debounce and Throttle

Debouncing prevents a function from being invoked until a specific period of time has passed since it was last called. "Run this function only if 100 milliseconds have passed without it being called." means "execute this function only if 100 milliseconds have passed without it being called."

Perhaps a function is called 1,000 times in a short burst over 3 seconds, and it is no longer invoked. Once the burst is ended, if you debounced it at 100 milliseconds, the function will only fire once, at 3.1 seconds. The debouncing timer is reset each time the function is called during the burst. While throttling limits the number of times a function can be called in a certain amount of time. "Run this function at once per 100 milliseconds." means "execute this function at once every 100 milliseconds."

Assume you would call this method 1,000 times in 10 seconds under typical circumstances. It would only execute that function 100 times if you throttled it to once every 100 milliseconds.

10,000ms (10s * 1,000)

Maximum calls: 10,000ms / 100ms throttling = 100

Use of Debouncing and Throttling in Real Life

  • If your user is spamming by clicking the button frequently, you can use throttle a button click event.
  • If we look at the window resize event where we use debouncing when the window size is fixed by the user only, you want to redraw the UI.
  • In the mouse move event, we should only display the mouse pointer coordinates if the user has reached the desired location. We use debouncing for that.

Frequently Asked Questions

  1. What is javascript?
    JavaScript (JS) is a programming language, which with HTML and CSS, is one of the crucial technologies of the World Wide Web. Over 97% of websites employ JavaScript for web page behavior on the client-side, with third-party libraries frequently incorporated.
     
  2. What is debounce?
    The debouncing method restricts the time-consuming tasks or functions from firing often. By doing so, it enhances the efficiency of the system. JavaScript provides the debounce() function to achieve debouncing. The debounce() function in JavaScript restricts a function from running again for a certain period of time. 
     
  3. What is throttling?
    Throttling can be achieved using the throttle() function used in websites. We use throttling to call a function after every millisecond or a particular time interval.
     
  4. What are the advantages of the throttling function?
    It prevents the function from being called frequently.
    It speeds up the website and limits the number of times a specific function is called.
     
  5. What are the use cases of debounce()?
    Debouncing a resize event handler is the first step.
    Do nothing while the user is dragging and dropping.
    In an autosave feature, debouncing a save function.
    Wait till the user has finished typing before making any Axios queries.
     
  6. What is Axios?
    Axios is a Javascript library that implements the Promise API, native to JS ES6, and used to make HTTP requests from node.js or XMLHttpRequests from the browser. 

Conclusion

In this article we have extensively discussed Debounce and Throttle.

We hope that this blog has helped you enhance your knowledge regarding encryption and if you would like to learn more, check out our articles on Find the Second Highest Element in an Array and Sort an Array with and without inbuilt methods

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Learning!

Live masterclass