Delay Your Js Events or Just Debounce
Hi Guys, today I want to speak about my search box problem, when you type something in the text area, you can combine this with 3 javascript events which are
- The
onKeyDown
event is triggered when the user presses a key. - The
onKeyUp
event is triggered when the user releases a key. - The
onKeyPress
event is triggered when the user presses & releases a key (onKeyDown
followed byonKeyUp
).
But it works a little bit differently than what we want, when using this event, it always watches and triggered the search function.
I searched furniture but it made a query for each letter, it causes many problems, you have to use a cancelation token on your backend otherwise it searches for every single step.
<!DOCTYPE html>
<html>
<body><p>A function is triggered when the user is pressing a key in the input field.</p><input type="text" name ="txtbox" onkeypress="waitForKey(document.getElementsByName('txtbox'))"><script>
var id = 0;function timer(text){
id = setTimeout(function (x) {
if(text && text.length > 0)console.log(text[0].value);
}, 1000)
};
function waitForKey(text) {
clearTimeout(id);
timer(text);
}</script>
</body>
</html>
Here is my basic code, I used the keypress event. When typing it will trigger for every single letter then, it set a timer for 1 second if you do not press any letter it will execute your search request. If you type before time is over, it will delete the timer and set new one.
Happy Code :)