How do I debounce a function in JavaScript?

clock icon

asked 404 days ago

message icon

1

eye icon

33

I have an input field where I fire an API request on every keystroke. This is causing too many network calls and poor performance. How can I debounce the function so it only fires after the user stops typing for, say, 300ms?

1 Answer

  • You can create a generic debounce helper:
1CopyEditfunction debounce(fn, delay = 300) {
2 let timer;
3 return function (...args) {
4 clearTimeout(timer);
5 timer = setTimeout(() => fn.apply(this, args), delay);
6 };
7}
8
1CopyEditfunction debounce(fn, delay = 300) {
2 let timer;
3 return function (...args) {
4 clearTimeout(timer);
5 timer = setTimeout(() => fn.apply(this, args), delay);
6 };
7}
8
  • Usage:
1CopyEditconst onInputChange = debounce((e) => {
2 fetchData(e.target.value);
3}, 300);
4
5document.querySelector('input').addEventListener('input', onInputChange);
6
1CopyEditconst onInputChange = debounce((e) => {
2 fetchData(e.target.value);
3}, 300);
4
5document.querySelector('input').addEventListener('input', onInputChange);
6

This wraps your real handler, cancelling any pending call until the user stops typing for delay milliseconds.

1

Write your answer here

Top Questions