avatarKirti K

Summary

The provided web content describes the implementation of a debounce function in JavaScript to optimize performance during user input events.

Abstract

The web content titled "JavaScript Day 44 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation" is a comprehensive tutorial aimed at beginners preparing for JavaScript interviews. It explains the concept of debouncing in JavaScript, a technique used to improve performance by limiting the frequency of function calls during events like typing in a search bar. The article breaks down the creation of a debounce function into detailed steps, from initializing the function to adding an event listener to an input field. It illustrates how debouncing can prevent unnecessary searches by waiting for a pause in typing before executing a search function, thus enhancing the user experience and efficiency of the code. The tutorial also includes HTML and JavaScript code examples to demonstrate the practical application of the debounce function. The content concludes with an encouragement for readers to subscribe and follow for more such insights, emphasizing the importance of sharing knowledge and treating people with respect.

Opinions

  • The author believes that understanding debouncing is crucial for mastering JavaScript basics and performing well in technical interviews.
  • The article suggests that debouncing is a key technique for optimizing event-handling functions, particularly in user interfaces that involve frequent events like typing.
  • The author conveys that the debounce function can significantly improve user experience by reducing the number of computations and avoiding unnecessary operations.
  • By providing a step-by-step guide, the author shows a preference for a structured and methodical approach to learning and implementing JavaScript concepts.
  • The encouragement to subscribe, clap, and follow indicates the author's commitment to continuous learning and community engagement.
  • The repeated emphasis on kindness and respect suggests that the author values a positive and supportive learning environment.

JavaScript Day 44 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation

100 Days of JavaScript Interview Prep: A Beginner’s Journey

JavaScript Day 44 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation

Question : How to create debounce function with example ?

Answer

In simple term, we decide to introduce a rule

Our friend can only talk after a short pause.

If they say something and then stay quiet for a little while, only then can they say something new.

This way, you can listen and write down what they’re saying without feeling overwhelmed.

In our web term also searching on a website.

Imagine we’re using a search bar on a website.

  1. Step 1 As we type each letter, the website immediately starts searching for matches and updating the results.
  2. Step 2 Now, if you type quickly, this means the search function gets called every time you press a key.

Here’s where debounce comes in

It helps prevent unnecessary searches

Let’s understand how we can about debounce.

  1. Step 1- Instead of searching every time you press a key, debounce waits for a moment of pause in your typing.
  2. Step 2 — If we stop typing for a brief moment, it then triggers the search.
  3. Step 3 — This way, it ensures that the search function is only called after we’ve finished typing or paused for a moment, making the search more efficient and responsive.

Hope this gives you an idea of what debounce is and how we can divide our code into steps.

Let’s start

STEP 1 — Initialization

It declares a function named debounce that takes two parameters:

func (the function to be debounced) and delay (the time delay in milliseconds).

function debounce(func, delay) {
     
  }

STEP 2 — Declaration of timeoutId

Declares a variable timeoutId to store the identifier for the timeout.

function debounce(func, delay) {
     let timeoutId;
}

STEP 3 — Returning a Function

Returns an inner function that will be invoked each time the debounced function is called.

function debounce(func, delay) {
     let timeoutId;
  return function() {
    
  }
}

STEP 4 — Handling arguments

function debounce(func, delay) {
     let timeoutId;
  return function() {
    const context = this;
     const args = arguments;
  }
}

STEP 5 — Clearing Previous Timeout

Clears the previous timeout if it exists, effectively resetting the timer.

function debounce(func, delay) {
    let timeoutId;
    return function() {
      const context = this;
      const args = arguments;
      clearTimeout(timeoutId);
   }
}
       

STEP 6— Clearing Previous Timeout:

Setting a New Timeout

Sets a new timeout using setTimeout. When this timeout elapses, it executes the provided function (func) with the captured context and arguments.

function debounce(func, delay) {
    let timeoutId;
    return function() {
      const context = this;
      const args = arguments;
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        func.apply(context, args);
      }, delay);
   }
}


STEP 7 — Create HTML with text input and output div for results

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Debounce Example</title>
</head>
<body>
  <input type="text" id="inputField" placeholder="Type something...">
  <div id="output"></div>

  <script>
    function debounce(func, delay) {
      let timeoutId;
      
      return function() {
        const context = this;
        const args = arguments;
        
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          func.apply(context, args);
        }, delay);
      };
    }
   

  </script>
</body>
</html>

STEP 8— Create handleInput function

  1. Retrieves the value of the input field with the ID 'inputField'.
  2. It assumes there's an HTML input element with that ID.
  3. Sets the innerText property of the element with the ID 'output' to the value of inputText.
  4. It will update the content of that element with the text typed into the input field.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Debounce Example</title>
</head>
<body>
  <input type="text" id="inputField" placeholder="Type something...">
  <div id="output"></div>

  <script>
    function debounce(func, delay) {
      let timeoutId;
      
      return function() {
        const context = this;
        const args = arguments;
        
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          func.apply(context, args);
        }, delay);
      };
    }

function handleInput() {
      const inputText = document.getElementById('inputField').value;
      document.getElementById('output').innerText = inputText;
    }

  </script>
</body>
</html>

STEP 9— Add debounce method

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Debounce Example</title>
</head>
<body>
  <input type="text" id="inputField" placeholder="Type something...">
  <div id="output"></div>

  <script>
    function debounce(func, delay) {
      let timeoutId;
      
      return function() {
        const context = this;
        const args = arguments;
        
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          func.apply(context, args);
        }, delay);
      };
    }

    function handleInput() {
      const inputText = document.getElementById('inputField').value;
      document.getElementById('output').innerText = inputText;
    }

    const debouncedHandleInput = debounce(handleInput, 500);

  </script>
</body>
</html>

STEP 10— Add Listener with debounce function

 
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Debounce Example</title>
</head>
<body>
  <input type="text" id="inputField" placeholder="Type something...">
  <div id="output"></div>

  <script>
    function debounce(func, delay) {
      let timeoutId;
      
      return function() {
        const context = this;
        const args = arguments;
        
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          func.apply(context, args);
        }, delay);
      };
    }

    function handleInput() {
      const inputText = document.getElementById('inputField').value;
      document.getElementById('output').innerText = inputText;
    }

    const debouncedHandleInput = debounce(handleInput, 500);
     const inputField = document.getElementById('inputField');
    inputField.addEventListener('input', debouncedHandleInput);

  </script>
</body>
</html>

This debounce function ensures that the provided func is only executed after a certain delay since the last invocation.

If func is called again within that delay, the previous call is cancelled, and the delay is reset.

STEP 11— Complete HTML with debounce code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Debounce Example</title>
</head>
<body>
  <input type="text" id="inputField" placeholder="Type something...">
  <div id="output"></div>

  <script>
    function debounce(func, delay) {
      let timeoutId;
      
      return function() {
        const context = this;
        const args = arguments;
        
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          func.apply(context, args);
        }, delay);
      };
    }

    function handleInput() {
      const inputText = document.getElementById('inputField').value;
      document.getElementById('output').innerText = inputText;
    }

    const debouncedHandleInput = debounce(handleInput, 500);

    const inputField = document.getElementById('inputField');
    inputField.addEventListener('input', debouncedHandleInput);
  </script>
</body>
</html>
HTML Code with debounce

Happy Coding and Stay Tuned :)

Kind is always cool !!!

Share knowledge to gain knowledge !!!!

Be kind and treat people with respect !!

If you find my blog helpful, then please subscribe, claps and follow to support :)

JavaScript Day 44 — Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation
Coding
JavaScript
Coding Interviews
Frontend Interviews
Programming
Recommended from ReadMedium