I have a script that searches my site for duplicate content as a user is typing in the title of a new post (just like on Quora). Right now it fires off a post request on keyup, leading to stacking of post requests.
Any ideas on the best way to avoid this?
$("#topic_title").keyup(function(){
var search_val=$(this).val();
$.post('/?post_type=topic&duplicate=1',{s:search_val},function(data){
if(data.length>0){
var results = $(data).find( '#results' );
$("#duplicates").html(results);
}
});
});
** Thanks for all of the quality answers! I went with the abort() method for simplicity. Works like a charm.
There are 2 things I will generally do in a situation like this:
Only send off the request after no key is pressed for a certain time period, say .5 a second. This way if a person is typing quickly, you don’t send off 10 requests, you just send one when they stop typing. This can be done by using
setTimeoutandclearTimeout.When a new request is sent, cancel the previous. This way there is only ever one active request. You really only care about the latest anyway. This can be done by using
abort().A rough outline: