w3resource

API Calls with Debounced Input Events in JavaScript

JavaScript Event Handling: Exercise-15 with Solution

Debounce Input Event

Write a JavaScript program that debounces the input event of a text box to wait before making an API call.

Solution 1: Throttling Scroll Event Using setTimeout

JavaScript Code:

// Debounce function using setTimeout
function debounce(callback, delay) {
  let timer; // Variable to store the timeout ID

  return function (...args) {
    clearTimeout(timer); // Clear the previous timeout
    timer = setTimeout(() => callback(...args), delay); // Set a new timeout
  };
}

// Input event callback
function handleInput(event) {
  console.log('API call for:', event.target.value); // Simulate API call
}

// Attach the debounced input event listener
const inputBox = document.createElement('input'); // Create a text box
inputBox.type = 'text';
inputBox.placeholder = 'Type something...'; // Add a placeholder
document.body.appendChild(inputBox); // Add the text box to the DOM

inputBox.addEventListener('input', debounce(handleInput, 300)); // Debounce input with 300ms delay

Output:

JavaScript

"API call for:"
"Ja"
"API call for:"
"Java"
"API call for:"
"JavaScript"

Explanation:

    1. Debounce Function:

    • The debounce function delays the execution of the callback until a specified time (delay) has passed since the last event.

    2. Callback:

    • handleInput logs the input value to simulate an API call.

    3. Text Box:

    • A text box is dynamically created and added to the DOM.

    4. Event Listener:

    • The input event is debounced to wait 300ms before invoking handleInput, reducing unnecessary API calls during rapid typing.

Solution 2: Debounce Using requestAnimationFrame

JavaScript Code:

// Debounce function using requestAnimationFrame
function debounceWithRAF(callback) {
  let frame; // Variable to store the frame ID

  return function (...args) {
    if (frame) cancelAnimationFrame(frame); // Cancel the previous frame
    frame = requestAnimationFrame(() => callback(...args)); // Request a new animation frame
  };
}

// Input event callback
function handleInput(event) {
  console.log('API call for:', event.target.value); // Simulate API call
}

// Attach the debounced input event listener
const inputBox = document.createElement('input'); // Create a text box
inputBox.type = 'text';
inputBox.placeholder = 'Type something...'; // Add a placeholder
document.body.appendChild(inputBox); // Add the text box to the DOM

inputBox.addEventListener('input', debounceWithRAF(handleInput)); // Debounce input using requestAnimationFrame

Output:

"API call for:"
"r"
"API call for:"
"re"
"API call for:"
"ret"
"API call for:"
"retu"
"API call for:"
"retur"
"API call for:"
"return"

Explanation:

    1. Debounce Function:

    • Uses requestAnimationFrame to delay the callback until the next browser repaint, ensuring efficient handling of rapid events.
    2. Callback:
    • handleInput logs the current input value to simulate an API call.

    3. Text Box:

    • A dynamically created input box is added to the DOM.

    4. Event Listener:

    • The input event is debounced using requestAnimationFrame, improving performance.

Live Demo:

See the Pen javascript-event-handling-exercise-15 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Event Handling Exercises Previous: Event Bubbling and stopPropagation in JavaScript.
Event Handling Exercises Next: Creating a Persistent Counter with JavaScript and LocalStorage.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.