JS DOM: debounce (delay input)

By Xah Lee. Date: . Last updated: .

Debounce (delay) user input

in html input text field, i want instant action (i use event input), but not when people is still typing. maybe a 0.3 second delay. how to do that?

clear and restart a timer on every input so the action only runs after the user stops typing for 300 ms.

<input id="myInput" type="text" placeholder="Type something…">
const input = document.getElementById("myInput");
let timeout;

input.addEventListener("input", () => {
 clearTimeout(timeout);
 timeout = setTimeout(() => {
  // Your action here (runs 300 ms after typing stops)
  console.log("Action:", input.value);
 }, 300);
});

Reusable debounce function

function debounce(fn, delay = 300) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}

const handleInput = debounce((e) => {
  console.log('Action:', e.target.value);
}, 300);

input.addEventListener('input', handleInput);

Debounce function, TypeScript version

function debounce<T extends (...args: any[]) => void>(
  fn: T,
  delay = 300
): (...args: Parameters<T>) => void {
  let timeout: ReturnType<typeof setTimeout> | undefined;
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}