I have a input field, where the user can be type a search string. This string should be send as an ajax post on keydown event:
$( "#inputField" ).keypress(function() {
// AJAX
});
With this function, the ajax post will send every keypress. For Example: The user wrote "Example" => 7 letters => 7 time ajax post
How can I make it better?
CodePudding user response:
You can use this small function, it works in such a way that it runs after the user finishes typing and delays
Sample code:
function debounce(callback, ms) {
var timer = 0;
return function() {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
// Sample:
$('#input').keyup(debounce(function (e) {
console.log('Time Ended!', this.value);
}, 800));
Try it:
function debounce(callback, ms) {
var timer = 0;
return function() {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
// Sample:
$('#input').keyup(debounce(function (e) {
console.log('Time Ended!', this.value);
}, 800));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<label for="input">Search:
<input id="input" type="text" placeholder="words..."/>
</label>