I’m having trouble understanding how JQueryUI’s autocomplete function deals with repeated keypresses resulting in asynchronous results. I needed something with similar functionality to it, but I can’t get the autocompleted results to come in properly. An Example:
$(document).ready(function() {
$('#textinput').live('keyup', function() {
$.get('bacon.php', function(data) {
$('#holder').html(data);
});
});
});
The problem is that if type quickly, the results often do not come back in the right order. If I type the word ‘KEY’, I may get back results for ‘K’, then ‘KEY’, and then ‘KE’, messing up the content of #holder. I notice that the JQueryUI autocomplete does not have this issue, but I can’t understand how it handles it.
I haven’t looked at jQuery’s Autocomplete functionality with respect to this particular issue, but what I do with my custom autocompletion scripts is I abort the XHR request if another keypress has been hit within a certain time frame. Something like this:
Basically, the throttle makes sure we wait 250 milliseconds before sending the request, in case the user is still typing (you can set this to whatever). The “xhr” variable keeps the XMLHttpRequest in a variable, and if we get another keypress and the response hasn’t come back yet, then we abort the previous one, making sure that only the latest one actually comes back with a response.
Hope that helps.
Good luck 🙂