Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add delay before sending new ajax request using jQuery

I have a list of links which point to html pages.

<ul id="item-list">
    <li><a href="assets/data/item1.html">Item 1</a></li> 
    <li><a href="assets/data/item2.html">Item 2</a></li>
    <li><a href="assets/data/item3.html">Item 3</a></li>
    <li><a href="assets/data/item3.html">Item 4</a></li>
</ul>

And I have a JavaScript(jQuery) which receives and appends the html to my document.

var request;
$('#item-list a').live('mouseover', function(event) {
    if (request)
        request.abort();
        request = null;
    
    request = $.ajax({
        url: $(this).attr('href'),
        type: 'POST',
        success: function(data) {
            $('body').append('<div>'+ data +'</div>')
        }
    });
});

I've tried to work with setTimeout() but it does not work as I expected.

    var request, timeout;
$('#item-list a').live('mouseover', function(event) {
    timeout = setTimeout(function(){
        if (request)
            request.abort();
            request = null;

        request = $.ajax({
            url: $(this).attr('href'),
            type: 'POST',
            success: function(data) {
                $('body').append('<div>'+ data +'</div>')
            }
           });
        }, 2000
    );
});

How can I tell jQuery to wait (500ms or 1000ms or …) on hover before sending the new request?

like image 895
gearsdigital Avatar asked Oct 19 '10 21:10

gearsdigital


2 Answers

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);
});
like image 190
netadictos Avatar answered Sep 22 '22 00:09

netadictos


$.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

like image 23
jellyfishtree Avatar answered Sep 20 '22 00:09

jellyfishtree