How to avoid overhead of continuous ajax request on keyup event?
var request;
function ajaxSearch(searchKey) {
/* if request is in-process, kill it */
if(request) {
request.abort();
};
request = $.ajax({
type: "get",
url: "http://example.com/ajaxRequestHandler/",
data: "action=search&searchkey=" + searchKey
}).done(function() {
/* process response */
/* response received, reset variable */
request = null;
});
}
To avoid multiple ajax requests; we can refer and implement a debounce function as mentioned in David Walsh's Blog post. It has some great insights of debounce function implementation from Underscore.js. The Debounce function will only fire once every fraction of a second instead of as quickly as it's triggered. It surely helps to restrict continuous network requests.
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var ajaxSearch = debounce(function() {
//send an AJAX network request.
$.ajax({
type: "get",
url: "http://example.com/ajaxRequestHandler/",
data: "action=search&searchkey=" + searchKey
}).done(function() {
/* process response */
});
//250 indicates the minimum time interval between the series of events being fired
}, 250);
$("#searchInput").keyup(function(){
ajaxSearch($("#searchInput").val());
});