How To Improve My Ajax Live Search By Doing Less Amount Of Requests
Solution 1:
Debounce will not work here as the problem is NOT in just one event listener having too many requests in a short amount of time, but with many independent event listeners firing one after the other.
Possible solutions:
Add a button eg
SEARCH
which will actually perform the search, instead of this being triggered by individual updates. This is a nice and simple solution to the many independent listeners problem.If you dont want to add a new button do sth like the following. Add a timeinterval with
setInterval
to perform a search with AJAX. And have a flag whether a search should be performed. Then when either listener on checkbox changes simply set the flag totrue
. Also if a request is already in progress do NOT make another AJAX request untill the current one finishes.
pseudocode follows:
var do_search = false, timer = null, doing_ajax = false, TROTTLE = 500;
timer = setTimeout(performSearch, TROTTLE);
functionperformSearch()
{
if ( !do_search || doing_ajax )
{
timer = setTimeout(performSearch, TROTTLE);
return;
}
doing_ajax = true;
do_search = false;
// do the ajax request here// ...// NOTE: on ajax complete reset the timer, eg timer = setTimeout(performSearch, TROTTLE);// and set doing_ajax = false;
}
// then your checkboxes listeners will simply update the do-search flag eg:
$('.searchsdgs input').on('ifChecked', function(event) {
var sdgid = event.target.value;
searchSelectedSdgs.push(sdgid);
updateURLParameters();
//performSearch();
do_search = true;
});
$('.searchsdgs input').on('ifUnchecked', function(event) {
var sdgid = event.target.value;
var arrayPos = $.inArray(sdgid, searchSelectedSdgs);
if (arrayPos > -1) {
searchSelectedSdgs.splice(arrayPos, 1);
}
//performSearch();
do_search = true;
});
$('.searchengagements input').on('ifChecked', function(event) {
var social_engagement_id = event.target.value;
searchSelectedEngagements.push(social_engagement_id);
updateURLParameters();
//performSearch();
do_search = true;
});
$('.searchengagements input').on('ifUnchecked', function(event) {
var social_engagement_id = event.target.value;
var arrayPos = $.inArray(social_engagement_id, searchSelectedEngagements);
if (arrayPos > -1) {
searchSelectedEngagements.splice(arrayPos, 1);
}
//performSearch();
do_search = true;
});
NOTE you can adjust the TROTTLE
interval to balance between more immediate interactivity and less AJAX requests. Experiment with different values to get a feeling for it for your app.
NOTE2 You can build on this example and make it like a multi-debounce function for example by clearing the timeout and resetting it in each individual listener (instead of simply setting do_search=true
you can set do_search=true
and clear the previous interval and reset it again). This will make sure only the last update will be performed.
Post a Comment for "How To Improve My Ajax Live Search By Doing Less Amount Of Requests"