Add delay before sending new ajax request using jQuery
I think that perhaps instead of aborting the request, you should control the ajax requests with a variable, for example, called processing=false
, that would be reset to false, in the success/error function.
Then you would only execute the function in setTimeout, if processing was false.
Something like:
var request, timeout;
var processing=false;
$('#item-list a').live('mouseover', function(event) {
timeout = setTimeout(function() {
if (!processing) {
processing=true;
request = $.ajax({
url: $(this).attr('href'),
type: 'POST',
success: function(data) {
processing=false;
$('body').append('<div>'+ data +'</div>')
}
});
}
}, 2000);
});
$.fn.extend( {
delayedAjax: function() {
setTimeout ($.ajax, 1000 );
}
});
$.fn.delayedAjax();
Seems to work but probably not the prettiest solution. Also, you need to add some code to pass the args & the timeout val if you want
You will need to have a variable that can act a countdown timer if you will, that a mouseout event will cancel as well...
$(function(){
$("#item-list a").live("mouseover",function(){
var a = $(this);
a.data("hovering","1");
setTimeout(function(){
if (a.data("hovering") == "1") {
// this would actually be your ajax call
alert(a.text());
}
}, 2000);
});
$("#item-list a").live("mouseout",function(){
$(this).data("hovering","0");
});
});