Here is my code:
$("input").on('keydown', function(){
$.ajax({
url : '/files/tags_autocomplete.php',
dataType : 'JSON',
success : function (tags) {
$("ul").html(tags.output);
}
});
});
My code suggests some tags (the ones that have a matched substring with what the user has written so far) to user as an autocomplete box when he is typing his tags.
What's my problem? My current code sends a new ajax request per each keydown. For example, if the user writes something
, my script sends 9 ajax requests which seems like a nightmare.
Anyway, how can I handle that? I mean do I need to implement a delay for sending? Something like "don't send the request until 1 sec after last character inserted"? or is there any better idea?
You could create a simple throttle mechanism
$("input").on('keydown', function(){
clearTimeout( $(this).data('timer'); )
var timer = setTimeout(function() {
$.ajax({
url : '/files/tags_autocomplete.php',
dataType : 'JSON',
success : function (tags) {
$("ul").html(tags.output);
}
});
}, 500);
$(this).data('timer', timer);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With