JS DOM: debounce (delay input)
js debounce
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?
(ai answer)
Use a debounce: 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…"> <script> 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); }); </script>
Reusable debounce helper
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);
That’s all you need. The action fires only after 0.3 s of inactivity.
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); }; }