I have search-bar (Text Field) component and according to what user types there it updates a list. The issue is that for each character that the user enters the list updates, so if they want to write Learn React
the list changes 11 times!
I need to do something that delays the function (updateList) calls, let's say make it called every 1 second even if it's called many times in a second.
any suggestion.
Asked
Active
Viewed 150 times
0

ILoveReactAndNode
- 281
- 5
- 16
-
Please add some code we can review and offer help with. – aviya.developer Oct 10 '18 at 18:49
-
Plenty of code out there that throttle or debounce – epascarello Oct 10 '18 at 18:50
-
yes debounce works, could you please add it as an answer? thanks – ILoveReactAndNode Oct 10 '18 at 18:53
-
1This problem has definitely been solved before. As pseudo-pseudo code, start by setting a timer on each keyDown event. Reset the timer on each new keyDown event if the timer doesn't end. Once it ends, fire the update! Simple! – Magnum Oct 10 '18 at 18:54
2 Answers
0
In Simple Way you can do this:
var debounceTimeout = null;
searchInput.on('change keyup', function(event){
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(searchEvents, 500);
});
also you can handling this by a lot of ways like set a var with bool value, and when success let it false and back to true when search trigger ..etc

Anees Hikmat Abu Hmiad
- 3,460
- 2
- 19
- 36
0
I create a JSFiddle to show you an example:
https://jsfiddle.net/kmo61q89/
Credits go to David Walsh (https://davidwalsh.name/javascript-debounce-function)
Add this debounce function to your code:
function debounce(func, wait, immediate) {
var timeout;
return function executedFunction() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Then, add an event listener to your input:
var input = document.getElementById("myInput");
var searchFunction = debounce(function() {
console.log('seach code here')
}, 250);
input.addEventListener('keyup', searchFunction);

Baral
- 3,103
- 2
- 19
- 28