Skip to content

Instantly share code, notes, and snippets.

@mirko77
Created October 29, 2015 16:39
Show Gist options
  • Save mirko77/4740df0c7cd45214a5da to your computer and use it in GitHub Desktop.
Save mirko77/4740df0c7cd45214a5da to your computer and use it in GitHub Desktop.
Throttling Ajax request for autocomplete
//populate lists with autocomplete suggestions based on project names on the server
dom_list.on('listviewbeforefilter', function (e, data) {
console.log('typing');
var $ul = $(this);
var $input = $(data.input);
var value = $input.val();
var html = '';
//wait a fifth of a second the user stops typing
var request_delay = 200;
$ul.html('');
//trigger request with more than 2 chars
if (value && value.length > 2) {
autocomplete_spinning_loader.removeClass('hidden');
$ul.html('<li class="autocomplete-spinner"><i class="fa fa-spinner fa-spin"></i></li>');
$ul.listview('refresh');
/* Throttle requests as the user is typing on a phone. We want to send as fewer requests as possible:
* Typing a new char will stop the previous ajax request, not tapping for a third of a second will let the request go through
*/
clearTimeout(request_timeout);
request_timeout = setTimeout(function () {
console.log('requesting');
$.ajax({
url: 'http://plus.epicollect.net/' + 'projects?q=' + value + '&limit=25',
dataType: 'json',
crossDomain: true,
success: function (response) {
autocomplete_spinning_loader.addClass('hidden');
$.each(response, function (i) {
html += '<li class="h-nav-item">' + response[i].name + '</li>';
});
$ul.html(html);
$ul.listview('refresh');
$ul.trigger('updatelayout');
},
error: function (request, status, error) {
autocomplete_spinning_loader.addClass('hidden');
}
});
}, request_delay);
}//if
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment