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.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that debounces a search input event to delay API calls until the user stops typing.
  • Write a JavaScript function that implements a debounce mechanism on an input field and triggers a callback after a pause.
  • Write a JavaScript program that debounces rapid input events and displays the final input value after a set delay.
  • Write a JavaScript function that optimizes a live data filtering process by debouncing the input event on user keystrokes.

Go to:


PREV : Event Capturing Example.
NEXT : LocalStorage Counter.

Improve this sample solution and post your code through Disqus.

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.